1 /* experimental tracking of heap allocations for easy reaping no matter what the code path is
3 * both tasks are in the same function to take advantage of local static variables that are
4 * persistent across calls but invisible to code outside the function.
6 * @param ptr NULL: calloc(nmemb, size), NULL-1: reap all, otherwise free(ptr)
7 * @param nmemb number of elements of size to allocate
8 * @param size size if each element
11 #include "heap_reap.h"
14 unsigned int heap_debug = 0;
18 struct mem_track *prev;
19 struct mem_track *next;
25 heap_and_reap(void *ptr, size_t nmemb, size_t size)
27 static struct mem_track *memalloc = NULL;
28 struct mem_track *tmp;
32 // allocate requested memory and 'hide' the struct mem_track at the end of it
33 size_t dwords = ((nmemb * size + sizeof(struct mem_track)) / 4) + 1;
35 if ((result = calloc(dwords, 4)) != NULL) {
36 tmp = (struct mem_track *) (result + (dwords * 4) - sizeof(struct mem_track) );
37 tmp->allocated = dwords * 4;
38 tmp->requested = nmemb * size;
47 fprintf(stderr, "heap req %08lx alloc %08lx @ %p\n", tmp->requested, tmp->allocated, tmp);
50 else { // free allocation
51 struct mem_track *p = memalloc;
53 if (ptr == NULL-1 || p->ptr == ptr) { // free all or a specific allocation
55 fprintf(stderr, "heap free %08lx @ %p\n", p->allocated, p);
58 p->prev->next = p->next;
60 p->next->prev = p->prev;
65 if (ptr != NULL-1) // only freeing a specific allocation