The following is an example of bad source code. The problem with the program is that it allocates memory, but doesn’t free the memory before exiting.
#include <stdlib.h>
int main() {}
1. The environment variable “MALLOC_TRACE” must be set to the path of the output file. Setting environment variables is slightly different on every shell type. In the BASH shell on Linux, the command is as follows:
MALLOC_TRACE=/home/YourUserName/path/to/program/MallocTraceOutputFile.txt export MALLOC_TRACE;
2. The required library (“mcheck.h”) must be included in the source code. This is done by adding the following line to the top of the .c or .cpp file, as shown below:
#include <mcheck.h>
3. The function “mtrace()” must be called before you start allocating memory. It is usually easiest to call mtrace() at the very beginning of the main function.
mtrace();
To delimitate the end of the traced space, the function "muntrace()" must be call.
muntrace();
4. The program should be compiled and run. Note that you need to use the -g option to enable profiling. In GCC on Linux, this can be done using the following commands:
gcc yourProgram.c -g ./a.out
5. The memory leak information will be reported in the file specified by the MALLOC_TRACE environment variable. The difficulty is, this file will be in a computer-readable format. Most Linux machines come with a console command called “mtrace”, that converts the computer file into human-readable text as shown below. If you do not have access to this console command, there is a perl script that can be downloaded and will accomplish the same task. mtrace follows the following syntax:
mtrace <exec_file_name> <malloc_trace_filename>
For example:
mtrace a.out MallocTraceOutputFile.txt
6. mtrace can be used with parallel computing but I process at a time, using a condition on the rank like:
if (my_rank==0) mtrace();
If the mtrace command reports “No Memory Leaks”, then all memory that was allocated in the last execution of that program was also released, which is the way it should be. If, on the other hand, mtrace gives output such as that below, it means the programmer still has some work to do.
Memory not freed: ----------------- Address Size Caller 0x08049910 0x4 at /home/sureshsathiah/tips/leak.c:9
The following is an example of great source code. It releases memory after it is allocated, and it uses mtrace to notify the programmer if there are memory leaks.
#include <stdlib.h>
#include <mcheck.h>
int main() {}
free(a); /* we free the memory we allocated so we don't have leaks */
muntrace();
return 0; /* exit */
}
mtracemtrace