Memory accounting routines for C

Managing memory is Hard. Very Hard. If you are programming in C you have a few options, notably valgrind. However, if you find yourself in the situation that I find myself in now in which valgrind cannot work, then you need something more.

For example, I’m writing code in ECL to call out to a few C libraries (that I’ve written myself). Valgrind is incompatible with ECL. In fact, it might just be incompatible with any GC-language. Whatever. I still need to keep accounting of my memory during testing.

Hence, I wrote this little replacement/wrapper for malloc. It stores all allocated memory as a list of blocks internally. It stores the filename, function and line number and the amount of memory that was allocated by each invocation of xmalloc. Usage is fairly standard:

int *foo = XMALLOC (sizeof *foo);
...
XMALLOC_FREE (foo);

 

Easy? You can look through the header for all the options (how to dump the list of blocks allocated, some general statistics on allocation, etc). Also, this can be turned off while the program is running, and normal malloc() is then used.

Enjoy.

Download the the xmalloc library

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>