Valgrind 的下载安装和使用 (centos7.6, 其他linux应该类同)

一、为什么需要Valgrind?

调试各种各样的崩溃问题,内存泄露问题,内存二次释放问题(double free),core dump,

Valgrind 是个开源的工具,功能很多。例如检查内存泄漏工具---memcheck。

二、Valgrind的下载和安装

1. 下载  (版本根据你当时的最新版本。官网: http://www.valgrind.org/downloads/)

wget https://sourceware.org/pub/valgrind/valgrind-3.15.0.tar.bz2

2. 解压

tar xjvf valgrind-3.15.0.tar.bz2

3. 安装

yum install autoconf
yum install automake
cd valgrind-3.15.0
chmod 775 autogen.sh
./autogen.sh
#如果提示aclocal相关信息,则需要 yum install autoconf automake
./configure
make
make install

查看是否安装成功,使用脚本

valgrind --version

Valgrind使用方法:

1. C++代码,测试用例

//hello.cpp
#include<iostream>
#include<stdio.h>

using namespace std;

int main()
{

    char *p = (char*)malloc(10);
    free(p);
    free(p);
    return 0;
}

2. 编译和链接

-g选项要添加,生成a.out

g++ hello.cpp -g

3. 运行和调试

valgrind --log-file=output.txt --tool=memcheck --leak-check=yes --show-reachable=yes ./a.out

4. 输出日志

其中--log-file 是输出日志到文件。去掉这个选项可以在终端显示上面观看

==128714== Memcheck, a memory error detector
==128714== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==128714== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==128714== Command: ./hello
==128714== Parent PID: 7668
==128714== 
==128714== Invalid free() / delete / delete[] / realloc()
==128714==    at 0x4C2AF5D: free (vg_replace_malloc.c:540)
==128714==    by 0x4008B2: main (hello.cpp:13)
==128714==  Address 0x5a23040 is 0 bytes inside a block of size 10 free'd
==128714==    at 0x4C2AF5D: free (vg_replace_malloc.c:540)
==128714==    by 0x40088A: main (hello.cpp:11)
==128714==  Block was alloc'd at
==128714==    at 0x4C29E63: malloc (vg_replace_malloc.c:309)
==128714==    by 0x40085E: main (hello.cpp:9)
==128714== 
==128714== 
==128714== HEAP SUMMARY:
==128714==     in use at exit: 0 bytes in 0 blocks
==128714==   total heap usage: 1 allocs, 2 frees, 10 bytes allocated
==128714== 
==128714== All heap blocks were freed -- no leaks are possible
==128714== 
==128714== For lists of detected and suppressed errors, rerun with: -s
==128714== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

上面的结果可以看到1次申请内存,两次释放内存。提示报错了。

发布了20 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qd1308504206/article/details/98964169