c there is no garbage collection mechanism, sometimes you apply for dynamic memory but forget to release, this is embarrassing (your program played a bandit role, have borrowed or good child). When you want to find out where the memory leaks, there is a huge amount of code that has a headache. Fortunately, the GNU C library provides some simple methods.
The two functions of mtrace and Muntrace help us to track dynamic memory usage. If we set the MALLOC_TRACE environment variable, the environment variable needs to point to a writable regular file under 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 will be recorded in the file.
Muntrace will uninstall the special handlers that were previously installed. This means that the dynamic memory trace is complete.
In general we call Muntrace before calling Mtrace,return at the beginning of the main function.
These two function prototypes are given below
#include <mecheck.h>void mtrace (void)void muntrace (void)
Usage examples:
#include <mcheck.h>
#include <stdlib.h>int main (intChar *argv[]) { #ifdef DEBUG mtrace (); #endif int *a = NULL malloc(sizeof(int )); // We don't call the free function here. return 0 ;}
In the above code, we did not call Muntrace (), nor is it recommended. The reason is that in Linux C not only are your programs tracking dynamic memory issues, C libraries are also used. If you call Muntrace (), that means the C library stops tracking dynamic memory.
If you use a macro to define the debug compilation file and execute the compiled executable, you will find that there is something in file.txt that we can't read. This content is for the machine to see. Most Linux distributions come with the Mtrace command (yes, the same name). Use the Mtrace command to turn machine-readable content into human reading. Use the following command:
file. txt
The above code executes the command after the result is as follows
Memory not freed:----------------------- Address Size Caller0x092a6378 0x4 at /root/tmp.c:9
It is clear that the 9th row of the malloc function, we did not call the corresponding free () function to release memory.
LINUXC Dynamic Memory Leak tracing method