mtrace 跟踪内存泄漏

来源:互联网 发布:adobe音频剪辑软件 编辑:程序博客网 时间:2024/04/19 17:48

mtrace是一个有效的工具来查看有没有内存泄漏。它会将内存出现的异常记录在日志中,而日志的路径是可以指定的。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<mcheck.h>
  4. #include<assert.h>

  5. int main()
  6. {

  7.         assert(!setenv("MALLOC_TRACE","./malloc.log",1));
  8.         mtrace();
  9.         int *p= malloc(100*sizeof(int));

  10.         return 0;
  11. }


我们看上面的代码,mtrace打开跟踪开关,我们malloc了400个字节的内存空间,但是我们并没有调用free将malloc出来的空间释放掉(当然函数退出也就释放了,但是这种释放不太优雅)。

    mtrace会将内存情况记录下来,记录的结果存在什么地方呢?由环境变量MALLOC_TRACE决定。所以实际上有两种设置环境变量的方法,一种情况就是代码中体现的:
    1 setenv函数设定环境变量 MALLOC_TRACE

  1. setenv("MALLOC_TRACE","./malloc.log",1)

   2 shell设定环境变量MALLOC_TRACE .
  1. export MALLOC_TRACE=~/program/C/MEM_CHECK/memcheck.log
下面看输出情况:
  1. root@libin:~/program/C/mem_bug# gcc -o test test.c -g
  2. root@libin:~/program/C/mem_bug# ./test
  3. root@libin:~/program/C/mem_bug# ll
  4. 总用量 28
  5. drwxr-xr-x 2 root root 4096 2012-04-03 12:17 ./
  6. drwxr-xr-x 36 root root 4096 2012-04-03 12:01 ../
  7. -rw-r--r-- 1 root root 155 2012-04-03 12:17 malloc.log
  8. -rwxr-xr-x 1 root root 8550 2012-04-03 12:17 test*
  9. -rw-r--r-- 1 root root 208 2012-04-03 12:17 test.c
  10. root@libin:~/program/C/mem_bug# mtrace ./test malloc.log
  11. - 0x09a68008 Free 3 was never alloc'd 0x1da8ef
  12. - 0x09a68028 Free 4 was never alloc'd 0x1da8f7

  13. Memory not freed:
  14. -----------------
  15. Address Size Caller
  16. 0x09a683b0 0x190 at /home/libin/program/C/mem_bug/test.c:11











0 0