Bit Of A Hack

Home Archives
logo

Keep up to date with Bit Of A Hack...

Seeing what C is freeing [Permalink]

Say that title again but faster, faster... FASTER! Now be quiet and read;

So, I wanted to see exactly what was being freed and when in a c program. The program has many calls to the free() function and so I didn't want to have to add a printf before each one. Instead I did this...

#define DEBUG_FREE_CALLS
#ifdef DEBUG_FREE_CALLS
#define free(x) (printf("Freeing %s, (%p)\n",#x,(void*)(x)),free(x))
#endif

It barely seems worth running it through an HTML syntax highlighter because it is just a macro.

Simply place this code at the top of the source file you are debugging and now whenever there is a call to free, for example;

free(counter);

You will see a message that looks something like this:

Freeing counter, (0x8ad8188)

Neat. You can disable this behaviour temporarily by commenting out the first line.

So what's going on? Well, the magic is in the third line, it replaces any call to free with a call to printf followed by a call to free. It's fairly simple. So if you have code like;

free(abc123);

Then this macro expands it to this;

(printf("Freeing %s, (%p)\n","abc123",(void*)(abc123)),free(abc123));

You will need to include stdio.h to get the printf function but that's all. what could be simpler?
It even accounts for bizarre cases where people have done strange things like the following;

free(foo), free(bar);

This syntax is a little odd but is still valid and so who am I to judge?

Just be careful when including this code that you don't do it before including stdlib.h as this file contains the extern declaration of free;

extern void free (void *__ptr) __THROW;

This expands to the following;

extern void (printf("Freeing %s, (%p)\n","void *__ptr",(void*)(void *__ptr)),free(void *__ptr)) __THROW;

Which gives a compiler error something like this;

/usr/include/stdlib.h:488:13: error: expected declaration specifiers or ‘...’ before string constant

Which isn't a great error message.

By .

comments powered by Disqus

This website uses cookies. If you don't like this, please stop using this site.