在Linux上快速安装Valgrind和简单使用Valgrind对C++程序进行内存泄漏检测

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨龙之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值