Created
January 9, 2017 23:06
-
-
Save hypernewbie/dc36884973a5325c6d1efcb8cd3f0c9f to your computer and use it in GitHub Desktop.
Minimal memory tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MEMTRACK_SZ 16000 | |
struct memory_tracker { | |
void* ptr[MEMTRACK_SZ]; | |
int opnums[MEMTRACK_SZ]; | |
int opnum = 0; | |
// Change this to break somewhere. | |
int break_opnum = -1; | |
memory_tracker() { | |
memset(ptr, 0, sizeof(void*) * MEMTRACK_SZ); | |
} | |
void* tr_malloc(void* p) { | |
if (opnum == break_opnum) { | |
assert(!"break_opnum hit. HALT."); | |
while(1); | |
} | |
for (int i = 0; i < MEMTRACK_SZ; i++) { | |
if (!ptr[i]) { | |
ptr[i] = p; | |
opnums[i] = opnum++; | |
return p; | |
} | |
} | |
assert(!"Out of tracking slots. Please increase MEMTRACK_SZ."); | |
return p; | |
} | |
void tr_free(void* p) { | |
if (opnum == break_opnum) { | |
assert(!"break_opnum hit. HALT."); | |
while(1); | |
} | |
for (int i = 0; i < MEMTRACK_SZ; i++) { | |
if (ptr[i] == p) { | |
ptr[i] = NULL; | |
opnums[i] = opnum++; | |
return; | |
} | |
} | |
assert(!"Untracked pointer free."); | |
} | |
void* tr_realloc(void* old, void* p) { | |
if (opnum == break_opnum) { | |
assert(!"break_opnum hit. HALT."); | |
while(1); | |
} | |
for (int i = 0; i < MEMTRACK_SZ; i++) { | |
if (ptr[i] == old) { | |
ptr[i] = p; | |
opnums[i] = opnum++; | |
return p; | |
} | |
} | |
assert(!"Untracked pointer realloc."); | |
return p; | |
} | |
void tr_print(void) | |
{ | |
printf("----- tracked memory pointers -----"); | |
for (int i = 0; i < MEMTRACK_SZ; i++) { | |
if (ptr[i]) { | |
printf(" ptr: %p opnum: %d\n", ptr[i], opnums[i]); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment