
Mtrace

codice_1 is the memory debugger included in the GNU C Library.
Use.
Note that codice_1 tool works only with single threaded applications. One thread could temporarily remove the hook while another thread could malloc memory at the sametime leading to missed allocations in a multithreaded application!
The function codice_1 installs handlers for codice_4, codice_5 and codice_6; the function codice_7 disables these handlers. Their prototypes, defined in the header file codice_8, are
 void codice_1(codice_10);
 void codice_7(codice_10);
The handlers log all memory allocations and frees to a file defined by the environment variable MALLOC_TRACE (if the variable is unset, describes an invalid filename, or describes a filename the user does not have permissions to, the handlers are not installed).
A perl script called codice_1, not to be confused with the function of the same name, is also distributed with the GNU C Library; the script parses through the output file and reports all allocations that were not freed.
Usage example.
Bad Source Code.
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.
int main(void) {
 int * a;
 a = malloc(sizeof(int)); /* allocate memory and assign it to the pointer */
 return 0; /* we exited the program without freeing memory */
 /* we should have released the allocated memory with the statement “free(a)” */
MTrace Usage.
$ MALLOC_TRACE=/home/YourUserName/path/to/program/MallocTraceOutputFile.txt
$ export MALLOC_TRACE
mtrace();
muntrace();
$ gcc yourProgram.c -g
$ ./a.out
$ mtrace <exec_file_name> <malloc_trace_filename> 
$ mtrace a.out MallocTraceOutputFile.txt
if (my_rank==0) mtrace();
MTrace Output.
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.
Good Source Code.
The following is an example of good source code. It releases memory after it is allocated, and it uses mtrace to notify the programmer if there are memory leaks.
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 */