mtrace检测内存泄露

简介:
mtrace是由glibc提供的一个工具,主要作用是查找内存泄露。


安装:
.....

使用:
① 给环境变量MALLOC_TRACE设定一个文件名,用于输出log。
② 待测代码中追加mtrace()和muntrace()。
③ 编译注意追加-g


实例:

① 手顺
export MALLOC_TRACE=/tmp/mtrace_log

gcc test.c -DDMALLOC_TRACE_TEST -g -o test

./test

unset MALLOC_TRACE

mtrace test /tmp/mtrace_log

② 代码

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <errno.h>
 4 #ifdef DMALLOC_TRACE_TEST
 5 #include <mcheck.h>
 6 #endif 
 7 
 8 void hello()
 9 {
10     char *hello;
11     hello = (char *) malloc(sizeof(char));
12     if (NULL == hello)
13     {
14         perror("Cannot allocate memory.");
15         return;
16     }
17 }
18 
19 int main()
20 {
21 #ifdef DMALLOC_TRACE_TEST
22     mtrace();
23 #endif
24     hello();
25     return 0;
26 }

 ③ 解析结果
Memory not freed:
-----------------
   Address     Size     Caller
0x0845b378      0x1  at /home/linux/develop/mem_test/1/test.c:16

原文地址:https://www.cnblogs.com/renhl/p/3302367.html