mtrace
用法:
#include <unistd.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <mcheck.h>
int main()
{
mtrace();//开始监测
int *p=(int *)malloc(4*sizeof(int));
free(p);
int *q=(int *)malloc(10*sizeof(int));//很明显这里的内存泄露了
muntrace();//关闭检测
return 0;
}
在环境变量中添加MALLOC_TRACE=test.log
$ export MALLOC_TRACE=test.log
调试模式下编译test.c
$ gcc test.c -o test -g
执行程序,会将检测的结果写入日志文件
$./test
使用mtrace分析log文件:
$ mtrace test test.log
结果如下:
Address Size Caller
0x0000000000f2d470 0x28 at /home/darmao/Desktop/test.c:10
告诉我们第十行内存泄露了。