Valgrind

Table of Contents

1. Valgrind

Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail.

参考:
The Valgrind Quick Start Guide: http://valgrind.org/docs/manual/quick-start.html
Valgrind User Manual: http://valgrind.org/docs/manual/manual.html
Using Valgrind to Find Memory Leaks and Invalid Memory Use: http://www.cprogramming.com/debugging/valgrind.html

2. Valgrind 查内存泄露实例

待测试 C 程序如下:

#include <stdlib.h>
int main()
{
    char *x = malloc(100);
    return 0;
}

用 valgrind 执行编译好的程序:

$ valgrind --tool=memcheck ./a.out

==12945== Memcheck, a memory error detector
==12945== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12945== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==12945== Command: ./a.out
==12945== 
==12945== 
==12945== HEAP SUMMARY:
==12945==     in use at exit: 100 bytes in 1 blocks
==12945==   total heap usage: 1 allocs, 0 frees, 100 bytes allocated
==12945== 
==12945== LEAK SUMMARY:
==12945==    definitely lost: 100 bytes in 1 blocks
==12945==    indirectly lost: 0 bytes in 0 blocks
==12945==      possibly lost: 0 bytes in 0 blocks
==12945==    still reachable: 0 bytes in 0 blocks
==12945==         suppressed: 0 bytes in 0 blocks
==12945== Rerun with --leak-check=full to see details of leaked memory
==12945== 
==12945== For counts of detected and suppressed errors, rerun with: -v
==12945== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

从上面报告中,可以看到 Valgrind 发现了 100 字节的内存泄露。

3. 其它内存检测工具

还有其它内存检测工具,如 Google 的 AddressSanitizer,这个工具已经和 LLVM 集成,不需要单独安装。

参考:https://github.com/google/sanitizers/wiki/AddressSanitizer

Author: cig01

Created: <2015-08-30 Sun>

Last updated: <2020-05-09 Sat>

Creator: Emacs 27.1 (Org mode 9.4)