Thursday, April 02, 2009

Memory leaks - mtrace

Identifying Memory Leaks in Linux for C++ Programs
Most C++ programmers agree that it can be harrowing trying to identify the memory leaks in a given program.
If you're working on the GNU/Linux platform, there's an interesting tool you can use to minimize the hassle of this task: mtrace.

Here's some background on mtrace:

You call the mtrace() function to log all memory leaks. The memory allocations and deallocations are logged to a text file pointed to by the environment variable—MALLOC_TRACE.
A Perl utility called mtrace parses the text file logged by your program and identifies the memory leaks.
The following code allocates memory, but does not essentially free it:

#include

int main() {
int *a;

a = malloc(sizeof(int)); //Allocate memory

*a = 7;
//Notice that we are not freeing memory before we end the program.

return EXIT_SUCCESS;
}

Now, see how to use mtrace to identify the memory leak:
Step 1: Setup MALLOC_TRACE environment variable to point to a file where mtrace needs to log the memory allocations:

setenv MALLOC_TRACE /home/karthik/temp/trace.txt

Step 2: Insert mtrace hooks into the program:

#include
#include /* Header file to include mtrace related functions */

int main() {
int *a;

mtrace(); /* This starts memory tracing.
This has to be done before we do a 'malloc' or we allocate memory. */

a = malloc(sizeof(int)); /* Allocate memory */

*a = 7;
/* Notice that we are not freeing memory before we end the program. */

return EXIT_SUCCESS;
}

Step 3: Compile the modified program with the debugging options turned on:

$ gcc -g -Wall -ansi -pedantic leak.c

Step 4: Run the program.
Step 5: Use the mtrace utility to retrieve the information. Here's what the syntax looks like:

mtrace

[akkumar@empress work]$ mtrace a.out ~/temp/trace.txt

Memory not freed:
-----------------
Address Size Caller
0x08049910 0x4 at /home/karthik/tips/leak.c:9

This precisely tells you that there is a potential memory leak at line 9:

a = malloc(sizeof(int)); /* Allocate memory */

mtrace is a GNU utility.
The code in this tip was tested on a Linux platform with the gcc 3.2.3.

Karthik Kumar Arun Kumar