url: https://blog.youkuaiyun.com/qq_24130227/article/details/119681441
示例:
#include <mcheck.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
mtrace(); // 开始跟踪
char *p = (char *)malloc(100);
free(p);
p = NULL;
p = (char *)malloc(100);
muntrace(); // 结束跟踪,并生成日志信息
return 0;
}
gcc -g test.c -o test
设置内存踪迹文件路径
export MALLOC_TRACE=./test.log // 当前目录下
./test
cat ./test.log
= Start
@ ./test:[0x400624] + 0x21ed450 0x64
@ ./test:[0x400634] - 0x21ed450
@ ./test:[0x400646] + 0x21ed450 0x64
= End
上述指令仅仅只是可以定位源码位置,但是没法分析存在内存泄漏的问题,因此需要通过下述指令分析日志信息(mtrace + 可执行文件路径 + 日志文件路径)。
mtrace <可执行文件路径> <日志文件路径>
# mtrace test ./test.log
Memory not freed:
-----------------
Address Size Caller
0x00000000021ed450 0x64 at /home/const/WorkSpace/memtest/test.c:14
具体看 参考url