Friday, December 08, 2006

Wrapping malloc/free

Recently I have come across a situation in which I was supposed to detect memory leak in our application. Since we have written our own memory for our application memory requirements, it become easy for me to tell there is no memory leak inside our code. Since memory consumption was continuously increasing we had confirmed there was a memory leak but not in our code. So the only remaining place where the leak could happen is library. Since we don’t have the source of the library we couldn’t confirm the leak. I started googling for memory leak related stuff and finally end up with a solution.

The first solution is hooking malloc/free. This can be done by assigning callback functions to these variables __malloc_hook/__free_hook. But this feature is not available in older glibc (like mine 2.95.3). So I skipped to the second solution, that is wrapping the malloc/free functions with the help of linker, so that every call to malloc/free will notify us and we can do stuffs like profiling, auditing and etc. Seems simple? Yeah, it is simple if know how glibc memory allocator works.

First add the wrapper functions in your source code like below

void* __wrap_malloc(size_t size)

// You can call the real malloc by __real_malloc
// You can do also profiling, like how many allocations,
// size of allocations and etc.

void* __wrap_realloc(void* oldptr, size_t size)


void __wrap_free(void* ptr)


Then use the following LDFLAGS for compiling your program

NOTE: Some linkers (like mine) are very sensitive to the way the parameters are passed, so check

Now any call to malloc/free will come to __wrap_malloc/__wrap_free functions

1 comment:

parallocity said...

Another way would be to scan the process map for lost pointers