A simple way to check memory leaks.
时间:2009-05-13 来源:tacoe
The mtrace tool helps diagnose the most common error when suing dynamic memory: failure to match allocations and deallocations. The are four steps to using mtrace, whilch is avilable with the GNU C library:
1. Modify the surce code to include <mcheck.h> and to invoke mtrace() as soom as the program starts, at the beginning of main. The call to mtrace turns on tracking of memory allocations and deallocations. Maybe, using define macro is a
good way!
2. Specify the name of a file to store information about all memory allocations and deallocations.
% export MALLOC_TRACE=memory.log
3. Run the program. All memory allocations and deallocations are stored in the logging file.
4. Using the mtrace command, anayze the memory allocations and deallocations to ensure that they match.
%mtrace my_program $MALLOC_TRACE.
Now, we write a simple exmple to show this:
malloc.c
#define MTRACE
#include <stdio.h>
#ifdef MTRACE
#include <mcheck.h>
#endif
int main(void)
{
#ifdef MTRACE
mtrace();
#endif
char *buf;
buf = malloc(sizeof(char) *100);
return 0;
}
the output just like follow:
[root@localhost leaks]# mtrace malloc $MALLOC_TRACE
Memory not freed:
-----------------
Address Size Caller
0x09747378 0x64 at 0x80483cb
All the metrials form <<Advanced Linux Programing>>. just for a note.
相关阅读 更多 +