如何使用Valgrind调试C++内存泄漏?

如何使用 Valgrind 调试 C++ 内存泄漏
Valgrind 是一个功能强大的内存调试器,可用于检测 C++ 程序中的内存泄漏、非法使用和分配问题。下面介绍如何使用 Valgrind 调试 C++ 内存泄漏:
1. 安装 Valg

如何使用valgrind调试c++内存泄漏?

如何使用 Valgrind 调试 C++ 内存泄漏

Valgrind 是一个功能强大的内存调试器,可用于检测 C++ 程序中的内存泄漏、非法使用和分配问题。下面介绍如何使用 Valgrind 调试 C++ 内存泄漏:

1. 安装 Valgrind

使用以下命令安装 Valgrind:

sudo apt install valgrind

登录后复制

2. 编译和调试

在编译程序时,添加 -g 标记以生成调试信息:

g++ -g my_program.cpp -o my_program

登录后复制

然后,使用 Valgrind 运行程序,并使用 –leak-check=full 标记来检查内存泄漏:

valgrind --leak-check=full ./my_program

登录后复制

3. 分析 Valgrind 输出

Valgrind 的输出将包含有关检测到的内存泄漏的信息。

实战案例

以下是一个模拟内存泄漏的简单 C++ 程序:

#include <iostream>

int* leak() {
  int* ptr = new int;
  return ptr;
}

int main() {
  int* ptr = leak();
  return 0;
}

登录后复制

编译并使用 Valgrind 运行此程序:

g++ -g leak.cpp -o leak
valgrind --leak-check=full ./leak

登录后复制

Valgrind 的输出将包含以下信息:

==27244== Memcheck, a memory error detector
==27244== Copyright (C) 2002-2017, and GNU GPL'd by, Julian Seward et al.
==27244== Using Valgrind-3.15.0.
==27244== Command: ./leak
==27244==
==27244== HEAP SUMMARY:
==27244==     in use at exit: 4 bytes in 1 blocks
==27244==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==27244==
==27244== LEAK SUMMARY:
==27244==    definitely lost: 4 bytes in 1 blocks
==27244==    indirectly lost: 0 bytes in 0 blocks
==27244==      possibly lost: 0 bytes in 0 blocks
==27244==    still reachable: 0 bytes in 0 blocks
==27244==         suppressed: 0 bytes in 0 blocks
==27244== Rerun with --leak-check=full to see what's still reachable
==27244==
==27244== For counts of detected and suppressed errors, rerun with: -v
==27244== Use --track-origins=yes to see where unfreed memory was allocated
==27244== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==27244==
==27244== 1 errors in context 0 of 1:
==27244== Invalid read of size 8
==27244==    at 0x4842E10: leak (leak.cpp:5)
==27244==    by 0x483D8E7: main (leak.cpp:12)
==27244==  Address 0x555555555600 is not stack'd, malloc'd or (recently) free'd
==27244==
==27244== LEAK SUMMARY:
==27244==    definitely lost: 0 bytes in 0 blocks
==27244==    indirectly lost: 0 bytes in 0 blocks
==27244==      possibly lost: 4 bytes in 1 blocks
==27244==    still reachable: 0 bytes in 0 blocks
==27244==         suppressed: 0 bytes in 0 blocks
==27244== Rerun with --leak-check=full to see what's still reachable
==27244==
==27244== For counts of detected and suppressed errors, rerun with: -v
==27244== Use --track-origins=yes to see where unfreed memory was allocated

登录后复制

此输出表明程序中存在 4 字节的内存泄漏,该泄漏来自函数 leak() 中未释放的 int 指针。

以上就是如何使用Valgrind调试C++内存泄漏?的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:weapp,转转请注明出处:https://www.dingdanghao.com/article/554960.html

(0)
上一篇 2024-05-31 11:20
下一篇 2024-05-31 12:00

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号