如何使用 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++内存泄漏?的详细内容。更多信息请关注PHP中文网其他相关文章!