admin管理员组

文章数量:1532440

你是否经常为自己所写程序的内存泄漏问题感到烦恼?当然保持良好的代码风格是最重要的,然而当你真正关注于程序逻辑的时候往往会忽略这个问题。Valgrind是一款用于内存调试、内存泄漏检测以及性能分析的软件开发工具。

下载地址:http://valgrind/downloads/current.html#current

直接按readme里介绍的进行编译安装就好了。

 

下面写个简单的程序测试之:

 

编译:

gcc test.c -o test -g

 

利用valgrind进行测试:

valgrind --leak-check=yes ./test

其中--leak-check选项表示对内存泄漏进行检查,valgrind参数非常多,--tool代表使用的工具,valgrind下有很多工具,其中memcheck是其默认工具。

 

输出结果如下:

==2901== Memcheck, a memory error detector
==2901== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2901== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==2901== Command: ./test
==2901==
==2901==
==2901== HEAP SUMMARY:
==2901==     in use at exit: 4 bytes in 1 blocks
==2901==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==2901==
==2901== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2901==    at 0x4024C6C: malloc (vg_replace_malloc.c:195)
==2901==    by 0x80483F8: main (test.c:3)
==2901==
==2901== LEAK SUMMARY:
==2901==    definitely lost: 4 bytes in 1 blocks
==2901==    indirectly lost: 0 bytes in 0 blocks
==2901==      possibly lost: 0 bytes in 0 blocks
==2901==    still reachable: 0 bytes in 0 blocks
==2901==         suppressed: 0 bytes in 0 blocks
==2901==
==2901== For counts of detected and suppressed errors, rerun with: -v
==2901== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 11 from 6)

其中第一列是pid,valgrind可以设置参数对所有子进程进行跟踪。结果显示malloc一次分配的内存没有释放。

 

下面对linux下ls命令做一个测试:

valgrind ls

 

输出如下:

==2993== Memcheck, a memory error detector
==2993== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2993== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==2993== Command: ls
==2993==
==2993==
==2993== HEAP SUMMARY:
==2993==     in use at exit: 12,600 bytes in 4 blocks
==2993==   total heap usage: 1,395 allocs, 1,391 frees, 110,152 bytes allocated
==2993==
==2993== LEAK SUMMARY:
==2993==    definitely lost: 120 bytes in 1 blocks
==2993==    indirectly lost: 0 bytes in 0 blocks
==2993==      possibly lost: 0 bytes in 0 blocks
==2993==    still reachable: 12,480 bytes in 3 blocks
==2993==         suppressed: 0 bytes in 0 blocks
==2993== Rerun with --leak-check=full to see details of leaked memory
==2993==
==2993== For counts of detected and suppressed errors, rerun with: -v
==2993== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 23 from 6)

怎么样?内存泄漏是不是无处不在?好的是只有120字节,linux表示影响不大 :)

使用--leak-check=full选项可以直接定位到代码所在的文件和对应的行,当然前提是编译时加上-g选项。

更加详细的内容可以参考Valgrind Documentation,在安装目录下的docs下。

本文标签: 内存调试工具valgrind