Checking for memory leaks with Mtrace

Source: Internet
Author: User
Tags perl script

http://blog.csdn.net/ixidof/article/details/6638066
Memory leak Check method (for Linux)
If you prefer to read the original document, refer to the "Allocation debugging" chapter of GLIBC info (performing info libc);
GLIBC provides a way to check for memory leaks, provided that your program allocates memory using GLIBC's standard functions (such as malloc, alloc ...):
1. call void Mtrace (void) at the beginning of the code that requires a memory leak check (declared in mcheck.h). Mtrace installs hooks for functions such as malloc to record memory allocation information. The end of the code that requires a memory leak check is called void Muntrace (void).
Note: In general, do not call Muntrace, but let the program end naturally. Because there might be some free memory code to run after Muntrace.
2. Compile the checked code in debug mode (-G or-GGDB)
3. Set the environment variable malloc_trace to a file name, and the file will have memory allocation information.
4. Run the checked program until the end 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), and if there is a memory leak, Mtrace will output The code location with the leaking memory, and the assigned quantity. Other things
1. Mtrace, Muntrace can be placed into the signal processing function (USR1, USR2) to dynamically perform memory leak check control.
2. Mtrace is a Perl code that you can read if you are interested in translating the symbolic address to the code text.
3. Again, try not to use Muntrace ()


For C + + Leak:
Methods to check for memory leaks in addition to the GLIBC provides you can also try some special programs, such as:
Ccmalloc (http://www.inf.ethz.ch/personal/biere/projects/ccmalloc/ccmalloc-english.html)
Mpatrol (http://www.cbmamiga.demon.co.uk/mpatrol/)
These two tools have a pretty good function and can perform a fairly thorough examination of the program.
Very strange, Redhat 9 actually without mtrace perl script, had to download the GCC source code compiled
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 methods are as follows:
VI A.C

[CPP]View PlainCopy
    1. 1 #include <mcheck.h>
    2. 2
    3. 3 int main ()
    4. 4 {
    5. 5 mtrace ();
    6. 6 malloc (10);
    7. 7 malloc (16);
    8. 8 return 0;
    9. 9}

$GCC-G A.C #记得编译带-G debug option
$export Malloc_trace=a.log
$./a.out
$unset Malloc_trace #记得执行完后unset变量, otherwise may run other commands may overwrite 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 exact location of the code that does not release the dynamic space is displayed.

Mtrace (3)                 Linux Programmer ' s Manual                mtrace (3)
NAMETop
       Mtrace, Muntrace-malloc tracing
SynopsisTop
       #include <mcheck.h>       void mtrace (void);       void Muntrace (void);
DESCRIPTIONTop
Themtrace() function installs hook functions for the memory-allocation functions (malloc (3), realloc (3) memalign (3), free (3)       ).  These hook functions record tracing information about memory allocation and deallocation. The tracing information can be used to discover memory leaks and attempts to free nonallocated memory in a pro       Gram. TheMuntrace() function disables the hook functions installed bymtrace(), so this tracing information is no longer recorded for the memory-allocation functions. If no hook functions were successfully installed bymtrace(),Muntrace() does nothing. Whenmtrace() is called, it checks the value of the environment variableMalloc_trace, which should contain the pathname of a file in which the tracing information was to be recorded.       If The pathname is successfully opened, it's truncated to zero length. IfMalloc_traceIs isn't set, or the pathname it specifies is invalid or isn't writable, then no hooks functions are installed, andmtrace() has no effect. In Set-user-id and Set-group-id programs,Malloc_traceis ignored, andmtrace() has no effect.
ATTRIBUTESTop
       For a explanation of the terms used in this section, see       Attributes (7).       ┌─────────────────────┬───────────────┬───────────┐       │Interface            Attribute       Value     │       ├─────────────────────┼───────────────┼───────────┤       │mtrace  Muntrace() │thread safety│mt-unsafe│       └─────────────────────┴───────────────┴───────────┘
Conforming toTop
       These functions is GNU extensions.
NOTESTop
       mtrace () is called once at the start of execution of       muntrace() is never called.       mtrace () is textual and not       designed to be human readable.  The GNU C Library provides a Perl       script, Mtrace (1), that interprets the trace log and produces human-       readable OU Tput.  For best results, the traced program should is       compiled with debugging enabled, so that line-number information is
   recorded in the executable.       mtrace () incurs a performance penalty (if       points to a valid, writable pathname).
BUGSTop
       The Line-number information produced by Mtrace (1) are not always precise:the line number references could refer to the       p Revious or       following (nonblank) line of the source code.
EXAMPLETop
The shell session below demonstrates the use of themtrace() function and the Mtrace (1) command in a program, which has memory leaks at the different locations. The demonstration uses the following program: $Cat t_mtrace.c#include <mcheck.h> #include <stdlib.h> #include <stdio.h> int m               Ain (int argc, char *argv[]) {int J;               Mtrace ();            for (j = 0; J < 2; j + +) malloc (100);             /* Never freed--a memory leak */calloc (16, 16);           /* Never freed--a memory leak */exit (exit_success); } When we run the program as follows.mtrace() diagnosed memory leaks at both different locations in the program: $cc-g t_mtrace.c-o t_mtrace$Export malloc_trace=/tmp/t$./t_mtrace$mtrace./t_mtrace $MALLOC _traceMemory not freed:-----------------Address Size Caller 0x084c9378 0x64 at/  Home/cecilia/t_mtrace.c:12 0x084c93e0 0x64 at/home/cecilia/t_mtrace.c:12 0x084c9448 0x100 at  /home/cecilia/t_mtrace.c:16 the first and messages about unfreed memory correspond to the both malloc (3) calls Inside the forLoop. The final message corresponds to the call to Calloc (3) (which in turn calls malloc (3)).
See ALSOTop
       Mtrace (1), malloc (3), Malloc_hook (3), Mcheck (3)
ColophonTop
       man-pages Project.  A       Description of the project, information about reporting bugs, and the       latest version of this page, can be found At       https://www.kernel.org/doc/man-pages/.  GNU                              2015-03-02                        mtrace (3)

Checking for memory leaks with Mtrace

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.