nlib
heap/object_tracking/object_tracking.cpp

A sample that associates a 24-bit integer value (color) and name with memory allocated using nmalloc.

You can now associate the following data with any allocated memory of 4096 bytes or more.
  • 24-bit integer value. This value allows a memory region to support RGB color.
  • String of up to 16 bytes, including a null terminating character. This string can contain data including a module name.
Since this function uses an empty region within the metadata for nmalloc, using the function will cause no side effect that memory arrangement on the heap will change.
void* red_ptr[100];
void* green_ptr[100];
void* blue_ptr[100];
static void red_thread(void*) {
for (int i = 0; i < 100; ++i) {
red_ptr[i] = nmalloc(4096);
nmalloc_query(NMALLOC_QUERY_SET_COLOR, red_ptr[i], 0xFF0000);
char name[16];
nlib_snprintf(NULL, name, sizeof(name), "red%d", i);
nmalloc_query(NMALLOC_QUERY_SET_NAME, red_ptr[i], name);
}
}
static void green_thread(void*) {
for (int i = 0; i < 100; ++i) {
green_ptr[i] = nmalloc(4096);
nmalloc_query(NMALLOC_QUERY_SET_COLOR, green_ptr[i], 0x00FF00);
char name[16];
nlib_snprintf(NULL, name, sizeof(name), "green%d", i);
nmalloc_query(NMALLOC_QUERY_SET_NAME, green_ptr[i], name);
}
}
static void blue_thread(void*) {
for (int i = 0; i < 100; ++i) {
blue_ptr[i] = nmalloc(4096);
nmalloc_query(NMALLOC_QUERY_SET_COLOR, blue_ptr[i], 0x00FF00);
char name[16];
nlib_snprintf(NULL, name, sizeof(name), "blue%d", i);
nmalloc_query(NMALLOC_QUERY_SET_NAME, blue_ptr[i], name);
}
}
static bool SampleMain(int, char**) {
nlib_thread red, green, blue;
e = nlib_thread_create(&red, NULL, red_thread, NULL);
if (e != 0) return false; // no cleanup for simplicity
e = nlib_thread_create(&green, NULL, green_thread, NULL);
if (e != 0) return false; // no cleanup for simplicity
e = nlib_thread_create(&blue, NULL, blue_thread, NULL);
if (e != 0) return false; // no cleanup for simplicity
for (int i = 0; i < 100; ++i) {
nfree(red_ptr[i]);
nfree(green_ptr[i]);
nfree(blue_ptr[i]);
}
return true;
}
NLIB_MAINFUNC