Tuesday, 29 May 2012

Memory Leakage Detection Tools - mtrace

'mtrace' can be used to detect memory leaks. 'mtrace' was written as part of the GNU C Library.

Lets consider following sample code that allocates memory but doesn't free it. All you need to do is add "mtrace()" before you call malloc(). And
muntrace() before returning from the program. Then set env variable MALLOC_TRACE with filepath of the mtrace_capture_file.

$ export MALLOC_TRACE="./trace.txt"

"./trace.txt" will record the mtrace_capture_data.

Sample code:

#include <stdlib.h>
#include <mcheck.h>

int main(void) {

        mtrace(); /* Starts the recording of memory allocations and releases */

        int* a = NULL;

        a = malloc(sizeof(int)); /* allocate memory and assign it to the pointer */
        if (a == NULL) {
                return 1; /* error */
        }

 //       free(a); /* we free the memory we allocated so we don't have leaks */
        muntrace();

        return 0; /* exit */

}

Steps:
1)export variable:
 $ export MALLOC_TRACE="./trace.txt"
2) Compile code
$ gcc -g mtrace_simple.c
3) execute folowing command to get trace
$ mtrace ./a.out trace.txt

you should get following o/p
Memory not freed:
-----------------
   Address     Size     Caller
0x092e8378      0x4  at /home/test/work/f1/mtrace_simple.c:10
Here  'mtrace' detects memory leakages.