[Switch] Linux C dynamic memory leakage tracking method, linux dynamic memory
Original article: http://www.cnblogs.com/san-fu-su/p/5737984.html
C. There is no garbage collection mechanism in it. Sometimes you have applied for dynamic memory but forgot to release it. This is embarrassing (your program plays the role of a robber, and it is a good child if you have any advantages ). When you want to find out where the memory is leaked, some users may have a headache when they invest a lot of code. Fortunately, the gnu c Library provides some simple methods.
Mtrace and muntrace functions help us track dynamic memory usage. The premise is that we have set the MALLOC_TRACE environment variable. To change the environment variable, we need to point to a standard file that can be written in our system. The procedure is as follows:
MALLOC_TRACE=/your/path/to/file.txtexport MALLOC_TRACE
Mtrace will install some special handlers for malloc, remalloc, and free. The usage of these functions is recorded in the file.
Muntrace uninstalls the previously installed special handlers. This means that the dynamic memory tracing is over.
In general, we call mtrace at the beginning of the main function, and call muntrace before return.
The two function prototypes are given below
#include<mecheck.h>void mtrace(void)void muntrace(void)
Instance used:
# Include <mcheck. h>
# Include <stdlib. h> int main (int argc, char * argv []) {# ifdef DEBUG mtrace (); # endif int * a = NULL a = malloc (sizeof (int )); // here we do not call the free function return 0 ;}
In the above Code, we did not call muntrace () and are not recommended. The reason is that in linux C, not only does your program track dynamic memory problems, but also uses the C library. If you call muntrace (), it means that the C library stops tracking dynamic memory.
If you use the macro definition debug to compile the files and execute the executable files behind the files, you will find some things that we cannot understand in file.txt. These contents are for the machine. Most linux releases have mtrace commands (correct, same name ). Use the mtrace command to convert the machine-read content to human-read. Run the following command:
mtrace a.out file.txt
The result of executing the command in the above Code is as follows:
Memory not freed:----------------------- Address Size Caller0x092a6378 0x4 at /root/tmp.c:9
Obviously, we didn't call the corresponding free () function to release the memory for the 9th-row malloc function.