Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1429444
  • 博文数量: 244
  • 博客积分: 3353
  • 博客等级: 中校
  • 技术积分: 3270
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-09 17:56
文章分类

全部博文(244)

文章存档

2023年(7)

2022年(7)

2021年(4)

2020年(1)

2019年(2)

2017年(2)

2016年(3)

2015年(11)

2014年(20)

2013年(10)

2012年(176)

分类:

2012-08-16 23:27:03

原文地址:mtrace 跟踪内存泄漏 作者:Bean_lee

    进来事情比较多,离职,入职,搬家,然后宽带没办好。进入新公司,很多精力花费在研究公司代码上,同时,需要学习shell和数据库 PHP,精力比较分散,所以好久没有写博客了。
    近乡情更怯,先发一篇比较简单的,热热身,找找感觉。

    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












阅读(1757) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~