nlib
heap/object_tracking/object_tracking.cpp

nmallocでアロケートしたメモリに24bit整数値(カラー)と名前を関連付けるサンプルです。

アロケートされた4096バイト以上の任意のメモリに対しての以下のデータの関連付けが可能となっています。
  • 24bit整数値。これはメモリ領域をRGBカラーに対応させることが可能です。
  • 16バイト(末尾のヌル文字を含む)以内の文字列。モジュール名等を入れることが可能です。
nmallocのメタデータ上の空き領域を利用するため、この機能の利用によりヒープ上のメモリ配置が変わるといった副作用はありません。
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