Valgrind安装与memcheck简单使用

安装 valgrind

sudo apt install valgrind

安装后,查看一下版本以确认安装成功

valgrind --version

输出形如以下版本号信息就表示安装成功

1
valgrind-3.11.0

使用 memcheck 检查内存泄漏

memleak.cpp

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
30
31
class A {
public:
A() {
a_arr = new int[5];
}
~A() {
delete[] a_arr;
}

private:
int* a_arr;
};

class B : public A {
public:
B() {
b_arr = new int[3];
}
~B() {
delete[] b_arr;
}

private:
int* b_arr;
};

int main() {
A* pa = new B();
delete pa;
return 0;
}
1
2
g++ -g memleak.cpp -o memleak
valgrind --tool=memcheck ./memleak

其中 --tool=memcheck 可以省略,因为 valgrind 的默认工具就是 memcheck
可以检查出类B对象中的12个字节(3个int)内存泄漏(见下方 definitely lost ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
==7661== Memcheck, a memory error detector
==7661== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==7661== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==7661== Command: ./memleak
==7661==
==7661==
==7661== HEAP SUMMARY:
==7661== in use at exit: 72,716 bytes in 2 blocks
==7661== total heap usage: 4 allocs, 2 frees, 72,752 bytes allocated
==7661==
==7661== LEAK SUMMARY:
==7661== definitely lost: 12 bytes in 1 blocks
==7661== indirectly lost: 0 bytes in 0 blocks
==7661== possibly lost: 0 bytes in 0 blocks
==7661== still reachable: 72,704 bytes in 1 blocks
==7661== suppressed: 0 bytes in 0 blocks
==7661== Rerun with --leak-check=full to see details of leaked memory
==7661==
==7661== For counts of detected and suppressed errors, rerun with: -v
==7661== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

使用 memcheck 检查 overlap

strncpy.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstring>
#include <iostream>

using namespace std;

int main() {
char s[60];
memset(s, '*', sizeof(s));
strcpy(s, "abcdefghijklmnopqrstuvwxyz");
strncpy(s + 26, s, 26);
for (int i = 0; i < 60; i++) cout << (s[i] ? s[i] : '_');
cout << '\n';
strncpy(s + 26, s, 27);
for (int i = 0; i < 60; i++) cout << (s[i] ? s[i] : '_');
cout << '\n';
return 0;
}
1
2
g++ -g strncpy.cpp -o strncpy
valgrind --tool=memcheck ./strncpy

此时memcheck会检查出重叠(overlap)错误。输出如下

1
2
3
==7561== Source and destination overlap in strncpy(0xfff0003d5, 0xfff0003bb, 27)
==7561== at 0x4C31626: __strncpy_sse2_unaligned (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7561== by 0x400951: main (strncpy.cpp:13)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×