Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1063206
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: LINUX

2009-11-19 12:48:44

  今天调试一段代码的时候,无意间发现内存泄漏,top命令查看到的进程内存持续增长。检查了半天的malloc和free,实在是没有找到问题。没办法,在网上查看了写帖子,知道有Valgrind这个东东,于是下下来,试了下,结果,就执行了一次便发现了程序的问题:
  使用参数valgrind --tool=memcheck --leak-check=yes ./hsvr_smp,

==16790==
==16790== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 16 from 2)
==16790== malloc/free: in use at exit: 1003488 bytes in 241 blocks.
==16790== malloc/free: 333 allocs, 92 frees, 1366168 bytes allocated.
==16790== For counts of detected errors, rerun with: -v
==16790== searching for pointers to 241 not-freed blocks.
==16790== checked 10218852 bytes.
==16790==
==16790== 3872 bytes in 44 blocks are possibly lost in loss record 18 of 21
==16790== at 0x1B904984: malloc (vg_replace_malloc.c:131)
==16790== by 0x80527C4: my_malloc (in /home/nari/exe/hsvr_smp3)
==16790== by 0x80686C1: mysql_store_result (in /home/nari/exe/hsvr_smp)
==16790== by 0x804B173: HDBChecktbl (hmysql.c:398)
==16790==
==16790== LEAK SUMMARY:
==16790== definitely lost: 0 bytes in 0 blocks.
==16790== possibly lost: 3872 bytes in 44 blocks.
==16790== still reachable: 999616 bytes in 197 blocks.
==16790== suppressed: 0 bytes in 0 blocks.
==16790== Reachable blocks (those to which a pointer was found) are not shown.
==16790== To see them, rerun with: --show-reachable=yes

   

  看到上面提示的函数栈,找到HDBChecktbl 函数内的 mysql_store_result 函数,原来
这段代码中调用了mysql_store_result却没有调用mysql_free_result。难怪自己没有找到malloc和free方面的错误。

  修改相关程序再执行 ,得到下面的结果:

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 16 from 2)
==16892== malloc/free: in use at exit: 278896 bytes in 65 blocks.
==16892== malloc/free: 165 allocs, 100 frees, 675016 bytes allocated.
==16892== For counts of detected errors, rerun with: -v
==16892== searching for pointers to 65 not-freed blocks.
==16892== checked 10203892 bytes.
==16892==
==16892== LEAK SUMMARY:
==16892== definitely lost: 0 bytes in 0 blocks.
==16892== possibly lost: 0 bytes in 0 blocks.
==16892== still reachable: 278896 bytes in 65 blocks.
==16892== suppressed: 0 bytes in 0 blocks.
==16892== Reachable blocks (those to which a pointer was found) are not shown.
==16892== To see them, rerun with: --show-reachable=yes


     由此看到,valgrind 可以很方便的指导程序员找到错误的地方。
阅读(673) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~