2023年8月17日,周四下午
目录
我使用的是CentOS 7,如果你使用的是其他Linux系统,操作也是大同小异
快速安装Valgrind
使用包管理器快速安装Valgrind
yum install valgrind
简单使用Valgrind
第一步
使用g++编译程序,添加 -g
选项以生成调试信息。这将允许Valgrind更准确地报告内存错误。
g++ -g program.cpp -o program
第二步
使用Valgrind运行编译后的程序。
valgrind --leak-check=full ./program
--leak-check=full
选项指示Valgrind对内存泄漏进行详细检查。
举例说明
第一步:待测试代码
//Test.cpp
#include<iostream>
using namespace std;
class Test{
};
void make_Test(){
Test* p=new Test();
}
int main(){
Test *p=new Test();
new Test[5];
make_Test();
}
第二步:用g++编译代码
g++ -g Test.cpp -o Test
第三步:使用Valgrind检测C++程序
valgrind --leak-check=full ./Test
第四步:得到检测结果
发现存在内存泄漏
[root@localhost linuxLearn]# valgrind --leak-check=full ./Test
==2054== Memcheck, a memory error detector
==2054== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2054== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==2054== Command: ./Test
==2054==
==2054==
==2054== HEAP SUMMARY:
==2054== in use at exit: 7 bytes in 3 blocks
==2054== total heap usage: 3 allocs, 0 frees, 7 bytes allocated
==2054==
==2054== 1 bytes in 1 blocks are definitely lost in loss record 1 of 3
==2054== at 0x4C2A593: operator new(unsigned long) (vg_replace_malloc.c:344)
==2054== by 0x400706: main (Test.cpp:13)
==2054==
==2054== 1 bytes in 1 blocks are definitely lost in loss record 2 of 3
==2054== at 0x4C2A593: operator new(unsigned long) (vg_replace_malloc.c:344)
==2054== by 0x4006EE: make_Test() (Test.cpp:9)
==2054== by 0x400719: main (Test.cpp:15)
==2054==
==2054== 5 bytes in 1 blocks are definitely lost in loss record 3 of 3
==2054== at 0x4C2AC38: operator new[](unsigned long) (vg_replace_malloc.c:433)
==2054== by 0x400714: main (Test.cpp:14)
==2054==
==2054== LEAK SUMMARY:
==2054== definitely lost: 7 bytes in 3 blocks
==2054== indirectly lost: 0 bytes in 0 blocks
==2054== possibly lost: 0 bytes in 0 blocks
==2054== still reachable: 0 bytes in 0 blocks
==2054== suppressed: 0 bytes in 0 blocks
==2054==
==2054== For lists of detected and suppressed errors, rerun with: -s
==2054== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)