Valgrind笔记(一):安装与Quick Start

安装

基于源码安装

  • 确认Valgrind最新版本
  • 下载源码:wget https://sourceware.org/pub/valgrind/valgrind-3.17.0.tar.bz2
  • 解压:tar xvf valgrind-3.17.0.tar.bz2
  • cd valgrind-3.17.0
  • 配置: ./configure
  • 编译:make install (可能需要root权限, sudo)

基于安装包安装

Ubuntu环境:sudo apt install valgrind

Quick Start

执行一个最简单的测试:

编写一段有bug的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdlib.h>

void f(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; // problem 1: heap block overrun
} // problem 2: memory leak -- x not freed

int main(void)
{
f();
return 0;
}

编译之(注意要编译选项要带上-g),编译出的可执行文件为test。用valgrind来执行test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$ valgrind ./test
==4597== Memcheck, a memory error detector
==4597== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4597== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==4597== Command: ./test
==4597==
==4597== Invalid write of size 4
==4597== at 0x10916B: f (test.c:6)
==4597== by 0x109180: main (test.c:11)
==4597== Address 0x4a47068 is 0 bytes after a block of size 40 alloc'd
==4597== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4597== by 0x10915E: f (test.c:5)
==4597== by 0x109180: main (test.c:11)
==4597==
==4597==
==4597== HEAP SUMMARY:
==4597== in use at exit: 40 bytes in 1 blocks
==4597== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==4597==
==4597== LEAK SUMMARY:
==4597== definitely lost: 40 bytes in 1 blocks
==4597== indirectly lost: 0 bytes in 0 blocks
==4597== possibly lost: 0 bytes in 0 blocks
==4597== still reachable: 0 bytes in 0 blocks
==4597== suppressed: 0 bytes in 0 blocks
==4597== Rerun with --leak-check=full to see details of leaked memory
==4597==
==4597== For lists of detected and suppressed errors, rerun with: -s
==4597== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

以上Valgrind给出的log中,已明确指示了错误的地方:

  • test.c 第6行,访问了一个超出malloc申请范围的地址。
  • 检测到一个40 bytes的内测泄漏。通过valgrind --leak-check=full ./test查看更详细的信息。

那么,我们就用valgrind --leak-check=full ./test 试试:

1
2
3
4
5
6
...
==179== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==179== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==179== by 0x10915E: f (test.c:5)
==179== by 0x109180: main (test.c:11)
...

Valgrind检测发现了在test.c第5行malloc的内存,没有被释放。

至此,Valgrind的简单demo就完成了。Valgrind(尤其是MemCheck tool)为C/C++程序员提供了很好的检查内存错误的工具。