I looked for existing answers first and saw that Valgrind is everyone’s favorite tool for memory leak debugging on linux. Unfortunately Valgrind does not seem to work for my purposes. I will try to explain why.
Constraints:
What I need is an equivalent of Microsoft’s UMDH: turn on stack tracing for each heap allocation, then at certain point of time dump all allocations grouped by stacks and ordered by allocation count in descending order. Our app ships on both Windows and Linux platforms, so I know that performance on Windows under UMDH is still tolerable.
Here are the tools/methods I considered
Did I miss anything? Are there any lightweight Valgrind options or existing LD_PRELOAD tool?
The most popular Valgrind tool is Memcheck, a memory-error detector that can detect issues such as memory leaks, invalid memory access, uses of undefined values and problems related to allocation and deallocation of heap memory.
GNU libc has built-in malloc debugging:
http://www.gnu.org/software/libc/manual/html_node/Allocation-Debugging.html
Use LD_PRELOAD to call mtrace()
from your own .so:
#include <mcheck.h> static void prepare(void) __attribute__((constructor)); static void prepare(void) { mtrace(); }
Compile it with:
gcc -shared -fPIC dbg.c -o dbg.so
Run it with:
export MALLOC_TRACE=out.txt LD_PRELOAD=./dbg.so ./my-leaky-program
Later inspect the output file:
mtrace ./my-leaky-program out.txt
And you will get something like:
Memory not freed: ----------------- Address Size Caller 0x0000000001bda460 0x96 at /tmp/test/src/test.c:7
Of course, feel free to write your own malloc hooks that dump the entire stack (calling backtrace() if you think that's going to help).
Lines numbers and/or function names will be obtainable if you kept debug info for the binary somewhere (e.g. the binary has some debug info built in, or you did objcopy --only-keep-debug my-leaky-program my-leaky-program.debug
).
Also, you could try Boehm's GC, it works as a leak detector too:
http://www.hpl.hp.com/personal/Hans_Boehm/gc/leak.html
I would like to advertise my just announced heaptrack utility, which should be just what you where looking for back then. You can find more information here: http://milianw.de/blog/heaptrack-a-heap-memory-profiler-for-linux
Compared to your heapwatch tool, the performance should be far better, as I use libunwind and later libbacktrace to delay the annotation of the backtrace with DWARF debug information.
I'd love to get more feedback on it, so try it out!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With