Sunday, March 29, 2009

Debugging Memory Allocations

Debugging memory allocations etc is always a pain, especially if you have memory leaks which dont cause errors directly. There are a wide variety of tools which facilitate detection, the most useful being Valgrind. The tool is awesome, and it definitely helps in this task. Also GNU libc has a wide ranging support for just this task.

But unfortunately you are not always lucky, and might find yourself working on systems other than Linux. Like FreeBSD. (Well you might have guessed that I am no fan of FreeBSD). Although Valgrind has a port to FreeBSD, it coredumps on startup. So in such dire circumstances you are left with no choice but to start from scratch.

Well everyone knows the standard mymalloc method, which is just a wrapper for the standard malloc call. However here is a more efficient method of doing it. Use the linker option "--wrap,malloc" which will make any references to malloc point to __wrap_malloc() (which you will be writing) and to call the actual malloc from inside your wrapper just call __actual_malloc().

The other option is to use the LD_PRELOAD, which loads your custom library, so any malloc calls are resolved to your wrapper calls. To call the actual malloc(), use the statement - "dlsym(RTLD_NEXT, "malloc");", which will give a function pointer to the actual malloc().

I know the blog is not too comprehensive on how to use these 2 facilities, but now that you know what can be done, just google them :)

No comments: