Memory leak detection of mtrace

----------------
Disclaimer: This article is CSDN bloggers 'sense of shame and then courage snail' original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/yf210yf/article/details/8022192

 

mtrace is a C function declarations and definitions in <mcheck.h>, the function prototype:

 void mtrace(void);

In fact mtrace is similar malloc_hook of malloc handler, the handler function just mtrace system has been written for you, but being the case, the system and know how you want to malloc / free records written where is it? To do this, call mtrace () before the first set MALLOC_TRACE environment variables:

 

#include <stdlib.h>
setenv("MALLOC_TRACE", "output_file_name", 1);  

 

[Output_file_name] is the name of the file to store test results.
But the format of the test results is the average person can not understand, but as long as the installation mtrace, it would have to mtrace of a Perl script, enter the following command in the shell:
mtrace [binary] output_file_name
brings its output_file_name converted to be understood statements.
For example: test program

#include <iostream>
#include <mcheck.h>
#include <stdlib.h>
using namespace std;
int main()
{
setenv("MALLOC_TRACE","output",1);
mtrace();
int *p1=new int;
int *p2=new int;
int *p3=(int*)malloc(sizeof(int));
int *p4=(int*)malloc(sizeof(int));

delete p1;
free(p3);
return 0;
}


Execution:
$ G ++ -Wall -g -o main main.cpp

Form

main

run

./main

Form

output file

View output file

$mtrace main output

Memory leaks can get the information
complete operational information is as follows:

snail@ubuntu:~/Java_workspace/3_内存泄露_mtrace$ g++ -Wall -g main.cpp -o main
main.cpp: In function ‘int main()’:
main.cpp:10:7: warning: unused variable ‘p2’
main.cpp:12:7: warning: unused variable ‘p4’
snail@ubuntu:~/Java_workspace/3_内存泄露_mtrace$ ./main
snail@ubuntu:~/Java_workspace/3_内存泄露_mtrace$ ls
main main.cpp output
snail@ubuntu:~/Java_workspace/3_内存泄露_mtrace$ mtrace main output
- 0x09aa1008 Free 8 was never alloc'd 0x8778cc
- 0x09aa10c8 Free 9 was never alloc'd 0x91556f
- 0x09aa10e0 Free 10 was never alloc'd 0x915577

Memory not freed:
-----------------
Address Size Caller
0x09aa1478 0x4 at 0xe7c679
0x09aa1498 0x4 at /home/snail/Java_workspace/3_内存泄露_mtrace/main.cpp:12
snail@ubuntu:~/Java_workspace/3_内存泄露_mtrace$

 

mtrace principle is to record each execution of malloc-free, if each has a corresponding malloc free, it means no memory leaks, memory leak problem for any non malloc / free what happened, and can not find out mtrace .
That is, for the New memory, can only detect a leak, but can not be located.
 

Programs compiled arm version, will be run to generate output files in the arm, copy the output files to linux, use mtrace main output, you can view the same memory problems

 

Guess you like

Origin www.cnblogs.com/nanqiang/p/11590083.html