valgrind使用

valgrind使用

 

1.前置条件

Compile your program with -g to include debugginginformation so that Memcheck's error messages include exact linenumbers. Using-O0 is also a goodidea, if you can tolerate the slowdown. With-O1 line numbers in error messages canbe inaccurate, although generally speaking running Memcheck on code compiledat-O1 works fairly well, and the speed improvementcompared to running-O0 is quite significant.Use of-O2 and above is not recommended asMemcheck occasionally reports uninitialised-value errors which don'treally exist.

使用valgrind检测的程序,在编译时候,需要加上 -g。尽量使用 -O0不进行代码编译优化。

 

 

2.检测内存泄漏:

1)编译程序:

用 -g 选项增加debug信息, -O0 或者 -O1 均可,-O0 运行非常缓慢,-O1 行号和错误信息会不准确。

不要使用-O2 或者更高的优化级别。

2)运行,检测是否有内存泄漏:

valgrind --leak-check=yes myprog arg1 arg2

用以下命令可以查看具体是哪个调用堆栈产生了内存泄漏(但运行速度缓慢):

valgrind --leak-check=full --show-leak-kinds=all myprog arg1 arg2

 

valgrind --leak-check=yes myprog arg1 arg2 

valgrind --leak-check=full --log-file=valgrind.log -v --track-origins=yes myprog arg1 arg2

堆栈不够大时加上--num-callers2:检测变量未赋初值--track-origins=yes

 

Valgrind是一个用于检测内存泄漏和内存错误的开源工具。下面是一些使用Valgrind的常见步骤: 1. 安装Valgrind- 在Linux上,您可以使用包管理器(如apt、yum)来安装Valgrind。例如,使用apt-get命令可以执行以下操作: ``` sudo apt-get install valgrind ``` 2. 编译您的程序: -编译您的程序时,使用-g选项以启用调试符号,并禁用任何优化选项。这样可以确保Valgrind能够正确分析和报告您的程序。 ``` g++ -g -o your_program your_source_file.cpp ``` 3. 运行Valgrind- 使用valgrind命令来运行您的程序并进行分析。以下是一些常用的选项: - --leak-check=full:启用完整的内存泄漏检查,以查找所有未释放的内存。 - --show-leak-kinds=all:显示所有内存泄漏的详细信息,包括可能的原因。 ``` valgrind --leak-check=full --show-leak-kinds=all ./your_program ``` 4. 分析Valgrind报告: - Valgrind会生成详细的报告,其中包含有关内存泄漏和错误的信息。请仔细阅读报告并查找任何潜在问题。 - 特别要注意报告中标记为"definitely lost"和"possibly lost"的内存泄漏信息。 请注意,Valgrind可能会对程序的运行速度产生一定的影响,并且在某些情况下可能会产生误报。因此,建议在测试环境中使用Valgrind,并仔细检查报告以确定是否存在真正的问题。 希望这些步骤可以帮助您使用Valgrind进行内存泄漏和错误检测!如果您有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值