awful allocation tracking macro
#include <stdlib.h> | |
#include <stdio.h> | |
struct Node { | |
size_t attempted_allocations; | |
size_t successful_allocations; | |
size_t size; | |
struct Node* next; | |
const char* file; | |
size_t line; | |
}; | |
static struct Node *head = NULL; | |
#define COMBINE(x, y) x ## y | |
#define EVAL(x, y) COMBINE(x, y) | |
#define NAME node | |
#define ALLOC(MEM, SZ) \ | |
static struct Node EVAL(NAME, __LINE__); \ | |
if (!EVAL(NAME, __LINE__).next) { \ | |
EVAL(NAME, __LINE__).line = __LINE__; \ | |
EVAL(NAME, __LINE__).file = __FILE__; \ | |
} \ | |
if (head && !EVAL(NAME, __LINE__).next) { \ | |
struct Node* last = head; \ | |
head = &EVAL(NAME, __LINE__); \ | |
head->next = last; \ | |
} \ | |
if (!head) head = &EVAL(NAME, __LINE__); \ | |
MEM = malloc(SZ); \ | |
EVAL(NAME, __LINE__).attempted_allocations += 1; \ | |
if (MEM) { \ | |
EVAL(NAME, __LINE__).successful_allocations += 1; \ | |
EVAL(NAME, __LINE__).size += SZ; \ | |
} \ | |
void do_thing() { | |
void *other_mem; | |
ALLOC(other_mem, 1024) | |
} | |
int main(int argc, char **argv) { | |
void *mem; | |
ALLOC(mem, 2048) | |
ALLOC(mem, 1024000000000000000) | |
do_thing(); | |
do_thing(); | |
struct Node *cur; | |
printf("allocations: \n"); | |
for (cur = head; cur != NULL; cur = cur->next) { | |
printf("allocation - attempted num: %zu, successful num: %zu, size: %zu, line: %zu, file: %s\n", | |
cur->attempted_allocations, cur->successful_allocations, cur->size, cur->line, cur->file); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment