A C library to track heap-allocated memory.
gearsix a3e0f29d3e REAMDE: removed title | 1 year ago | |
---|---|---|
Makefile | 2 years ago | |
README.md | 1 year ago | |
TODO.txt | 3 years ago | |
original-draft.c | 2 years ago | |
test.c | 2 years ago | |
tralloc.c | 2 years ago | |
tralloc.h | 2 years ago |
An C libray for tracking the size of heap-allocated memory blocks.
This is more of a proof-of-concept than anything and I wouldn't recommend using it in production. There's an accompanying article here: Tracking Allocations in C
This library provides several functions that act as wrappers around the stdlib memory allocation functions to provide information on the number of heap-allocated bytes for individual pointers and overall.
It's implemented with functions the act as stdlib wrappers so that it can sit ontop of whatever stdlib implementation you're using. The downside of this is that it's unable to track any allocations made without these wrappers.
There are also a few usability pitfalls:
This was done more as a personal exercise than anything, most of the time in C you'll track allocated memory yourself. This was just a cool idea I got carried away with.
tralloc_realloc()
, tralloc_allocsiz()
or
tralloc_free
on an address not returned by one of the tralloc stdlib
wrapper functions.malloc
instead of tr_malloc
, use a macro.
See test.c
for an example of this.tralloc_siz
size_t tralloc_siz();
Returns the number of bytes heap-allocated by tralloc memory allocation functions.
tralloc_limit
size_t tralloc_limit();
Returns the maximum limit set on tralloc_siz
.
If 0 is returned, there is no limit (returns 0 by default).
tralloc_setlimit
size_t tralloc_setlimit(size_t n);
Sets the maximum limit on tralloc_siz
.
If this limit is reached, then tralloc alloc functions will fail and
return NULL.
Returns n
if successful and 0 if unsuccessful.
tralloc_allocsiz
size_t tralloc_allocsiz(void *ptr);
Returns number of bytes allocated for ptr
.
ptr
must be a the address returned by a tralloc allocation.
These functions behave exactly the same and their stdlib counterparts.
The only difference is that they will also add the memory overhead
required to track the number of allocated bytes for each pointer
(which sizeof(size_t)
per-pointer) and increment/decrement the
tracked heapsiz accordingly.
This overhead is stored at index [-1] of the returned pointers and
used by functions within the library for tracking the heapsiz.
tralloc_malloc
void *tralloc_malloc(size_t n);
tralloc_calloc
void *tralloc_calloc(size_t num, size_t n);
tralloc_realloc
void *tralloc_realloc(void *ptr, size_t n);
ptr
must be a the address returned by a tralloc allocation.
tralloc_free
void tralloc_free(void *ptr);
ptr
must be a the address returned by a tralloc allocation.