参考
安装步骤
首先进入一个自定义的文件夹
例如:cd ~/valgrind/
- 下载安装包
- 解压缩
tar -xf valgrind-xxx.tar.bz2 # xxx -=> 版本号
make
A.
B.sudo apt-get install automake
C.sudo apt-get install autoconf
D.cd valgrind-xxx
E../autogen.sh
F../configure
G.make -jn # n: 并行数,依据自己的cpu核心判断,2,4,8 足够
sudo make install
测试
安装是否成功
valgrind --version
# 输出 valgrind-3.22.0
是否正常使用
- 写个
错误
的c++程序
//test.cpp
#include <iostream>
using namespace std;
// 有越界行为
int main()
{
int *a = new int[10];
cout << "ook" << endl;
a[9] = 10;
a[10] = 11;
return 0;
}
- 编译
- //-g:让
memcheck
工具可以取到出错的具体行号g++ test.cpp -g -o test valgrind --tool=memcheck --log-file=test.log --leak-check=yes ./test
- 查看
.log
文件cat test.log
- 如果报错
请安装valgrind: Note that if you are debugging a 32 bit process on a valgrind: 64 bit system, you will need a corresponding 32 bit debuginfo valgrind: package (e.g. libc6-dbg:i386). valgrind: Cannot continue -- exiting now. Sorry.
sudo apt-get install libc6-dbg
- 正常
可以查看第一篇参考文献看具体含义==35072== Memcheck, a memory error detector ==35072== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al. ==35072== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info ==35072== Command: ./test1_g ==35072== Parent PID: 4122 ==35072== ==35072== Invalid write of size 4 ==35072== at 0x109224: main (test1.cpp:10) ==35072== Address 0x4ddaca8 is 0 bytes after a block of size 40 alloc'd ==35072== at 0x484A703: operator new[](unsigned long) (vg_replace_malloc.c:725) ==35072== by 0x1091DE: main (test1.cpp:7) ==35072== ==35072== ==35072== HEAP SUMMARY: ==35072== in use at exit: 40 bytes in 1 blocks ==35072== total heap usage: 3 allocs, 2 frees, 73,768 bytes allocated ==35072== ==35072== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==35072== at 0x484A703: operator new[](unsigned long) (vg_replace_malloc.c:725) ==35072== by 0x1091DE: main (test1.cpp:7) ==35072== ==35072== LEAK SUMMARY: ==35072== definitely lost: 40 bytes in 1 blocks ==35072== indirectly lost: 0 bytes in 0 blocks ==35072== possibly lost: 0 bytes in 0 blocks ==35072== still reachable: 0 bytes in 0 blocks ==35072== suppressed: 0 bytes in 0 blocks ==35072== ==35072== For lists of detected and suppressed errors, rerun with: -s ==35072== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
感谢
忠心感谢参考文章的作者!