Finding Memory Leaks Using mtrace
When testing code on small samples, small problems such as memory leaks are often undetectable. However, once the program is run on a larger scale, existing memory leaks become larger problems; they often will cause a program to crash or to swap extensively (slowing performance drastically), and also affect any other programs running on the same system by reducing available memory.
To help avoid, or more often fix, such memory leaks, there are many tools available. One within the GNU platform is called mtrace.
Steps to Profiling a Program
- Add a call to mtrace() at the very start of your main function, and include mcheck.h in the file containing the main program.
- Compile the program with debug options set (i.e. the '-g' switch)
- export a variable called MALLOC_TRACE which contains a filename where the trace data should be stored. Example: export MALLOC_TRACE=mtrace.out
- Run the program, once
- Run 'mtrace my_program mtrace.out' to view the output
1. Add the mtrace() call
mtrace works by adding hooks into calls which allocate and deallocate memory, logging these calls, and reporting on any mis-matches between the recorded allocations and deallocations. In order t