Valgrind 检测程序内存使用

Valgrind是用于构建动态分析工具的探测框架。它包括一个工具集,每个工具执行某种类型的调试、分析或类似的任务,以帮助完善你的程序。Valgrind的架构是模块化的,所以可以容易地创建新的工具而又不会扰乱现有的结构。

许多有用的工具被作为标准而提供。

  1. Memcheck是一个内存错误检测器。它有助于使你的程序,尤其是那些用C和C++写的程序,更加准确。
  2. Cachegrind是一个缓存和分支预测分析器。它有助于使你的程序运行更快。
  3. Callgrind是一个调用图缓存生成分析器。它与Cachegrind的功能有重叠,但也收集Cachegrind不收集的一些信息。
  4. Helgrind是一个线程错误检测器。它有助于使你的多线程程序更加准确。
  5. DRD也是一个线程错误检测器。它和Helgrind相似,但使用不同的分析技术,所以可能找到不同的问题。
  6. Massif是一个堆分析器。它有助于使你的程序使用更少的内存。
  7. DHAT是另一种不同的堆分析器。它有助于理解块的生命期、块的使用和布局的低效等问题。
  8. SGcheck是一个实验工具,用来检测堆和全局数组的溢出。它的功能和Memcheck互补:SGcheck找到Memcheck无法找到的问题,反之亦然。
  9. BBV是个实验性质的SimPoint基本块矢量生成器。它对于进行计算机架构的研究和开发很有用处。

也有一些对大多数用户没有用的小工具:Lackey是演示仪器基础的示例工具;Nulgrind是一个最小化的Valgrind工具,不做分析或者操作,仅用于测试目的。

在这篇文章我们将关注“memcheck”工具。

在命令行下:

#valgrind --tool=memcheck --leak-check=full ./test

test 为可执行程序名称

编写程序:

int leak_test()
{
  char *p = (char *)malloc(10000);
  return 0;
}

内存泄漏输出:

==23079== HEAP SUMMARY:
==23079== in use at exit: 10,000 bytes in 1 blocks
==23079== total heap usage: 1 allocs, 0 frees, 10,000 bytes allocated
==23079==
==23079== 10,000 bytes in 1 blocks are definitely lost in loss record 1 of 1
==23079== at 0x4C2DBF6: malloc (vg_replace_malloc.c:299)
==23079== by 0x4005E7: leak_test (in /home/lin/test/memory/test)
==23079== by 0x40068C: main (in /home/lin/test/memory/test)
==23079==
==23079== LEAK SUMMARY:
==23079== definitely lost: 10,000 bytes in 1 blocks
==23079== indirectly lost: 0 bytes in 0 blocks
==23079== possibly lost: 0 bytes in 0 blocks
==23079== still reachable: 0 bytes in 0 blocks
==23079== suppressed: 0 bytes in 0 blocks
==23079==
==23079== For counts of detected and suppressed errors, rerun with: -v
==23079== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

使用非初始化变量:

int uninit_test()
{
int a[5];
int i = 0, s = 0;
//a[0] = a[1] = a[2] = a[3] = a[4] = 0;
a[0] = a[1] = a[2] = a[3] = 0;
for ( i = 0; i < 5; i++)
{
s += a[i];
}
printf("s = %d\r\n", s);
return 0;
}

检测程序输出:

==23175== Conditional jump or move depends on uninitialised value(s)
==23175== at 0x4E87CE2: vfprintf (vfprintf.c:1631)
==23175== by 0x4E8F898: printf (printf.c:33)
==23175== by 0x400663: uninit_test (in /home/lin/test/memory/test)
==23175== by 0x40068C: main (in /home/lin/test/memory/test)
==23175==
s = 4196000
==23175==
==23175== HEAP SUMMARY:
==23175== in use at exit: 0 bytes in 0 blocks
==23175== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==23175==
==23175== All heap blocks were freed -- no leaks are possible
==23175==
==23175== For counts of detected and suppressed errors, rerun with: -v
==23175== Use --track-origins=yes to see where uninitialised values come from
==23175== ERROR SUMMARY: 20 errors from 8 contexts (suppressed: 0 from 0)

[参考文档]

http://www.oschina.net/translate/valgrind-memcheck

http://blog.csdn.net/sduliulun/article/details/7732906

http://blog.csdn.net/destina/article/details/6198443

上一篇:Type Call requires API level 11 (current min is 8)解决办法


下一篇:valgrind检查代码内存泄漏,5种内存泄漏情况