Article Source: http://lagignition.blog.163.com/blog/static/128730023201072421016361/
Memory leakage check method (for Linux)
If you want to read the original document, see the "Allocation debugging" chapter in glibc Info (execute info libc );
Glibc provides a method to check for memory leaks, provided that your program uses standard glibc functions to allocate memory (such as malloc, alloc ...):
1. call void mtrace (void) (in the mcheck. h ). mtrace installs hooks for functions such as malloc to record memory allocation information. call void muntrace (void) at the end of the Code that requires memory leak check ).
Note: In general, do not call muntrace, but let the program end naturally, because some memory Code may not run until muntrace is released.
2. Compile the checked code in debug mode (-G or-ggdb)
3. Set the environment variable malloc_trace to a file name, which contains memory allocation information.
4. Run the checked program until it is finished or muntrace is called.
5. use the mtrace command to parse the memory allocation log file ($ malloc_trace), (mtrace Foo $ malloc_trace, where foo is the executible name), if there is a memory leakage, mtrace will output the code location allocated with leaked memory and the allocation quantity. other things
1. mtrace and muntrace can be placed into the signal processing function (usr1, usr2) to dynamically check and control memory leakage.
2. mtrace is a Perl code. If you are interested in the conversion of symbolic addresses and code texts, read it.
3. Again, try not to use muntrace ()
For C ++ leak:
In addition to glibc, you can also try some special programs to check for Memory leakage. For example:
Ccmalloc (http://www.inf.ethz.ch/personal/biere/projects/ccmalloc/ccmalloc-english.html)
Mpatrol (http://www.cbmamiga.demon.co.uk/mpatrol)
The functions of these two tools are quite good, and the program can be thoroughly checked.
It is strange that RedHat 9 does not contain the mtrace Perl script, so we have to download the GCC source code and compile it.
Wget -- passive-FTP ftp://rpmfind.net/linux/redhat/9/en/ OS /i386/SRPMS/glibc-2.3.2-11.9.src.rpm
Rpm-IVH glibc *. SRC. rpm
CD/usr/src/RedHat/specs/
Rpmbuild-Ba glibc-9.spec
CD/var/tmp/glibc-2.3.2-root/usr/bin/
CP mtrace/usr/bin/
The debugging method is as follows:
Vi a. C
1 #include <mcheck.h>2 3 int main()4 {5 mtrace();6 malloc(10);7 malloc(16);8 return 0;9 }
$ Gcc-g a. C # Remember to compile the "-G" debugging Option
$ Export malloc_trace = A. Log
$./A. Out
$ Unset malloc_trace # Remember the unset variable after execution; otherwise, other commands may overwrite the log
$ Mtrace A. Out A. Log
Memory not freed:
-----------------
Address size caller
0x09b08378 0xa at/XXX/a. C: 6
0x09b08388 0x10 at/XXX/a. C: 7
As you can see, the location of the Code that does not release the dynamic space is displayed.