Cara menggunakan Valgrind untuk nyahpepijat kebocoran memori C++
Valgrind ialah penyahpepijat memori yang berkuasa yang boleh digunakan untuk mengesan kebocoran memori, penggunaan haram dan isu peruntukan dalam program C++. Begini cara menggunakan Valgrind untuk menyahpepijat kebocoran memori C++:
1. Pasang Valgrind
Gunakan arahan berikut untuk memasang Valgrind:
sudo apt install valgrind
2. Kompil dan nyahpepijat > -g< /code> bendera untuk menjana maklumat penyahpepijatan:
g++ -g my_program.cpp -o my_program
Kemudian, gunakan Valgrind untuk menjalankan program dan gunakan bendera --leak-check=full
untuk menyemak kebocoran memori: -g
标记以生成调试信息:
valgrind --leak-check=full ./my_program
然后,使用 Valgrind 运行程序,并使用 --leak-check=full
标记来检查内存泄漏:
#include <iostream> int* leak() { int* ptr = new int; return ptr; } int main() { int* ptr = leak(); return 0; }
3. 分析 Valgrind 输出
Valgrind 的输出将包含有关检测到的内存泄漏的信息。
实战案例
以下是一个模拟内存泄漏的简单 C++ 程序:
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
Valgrind 的输出将包含以下信息:
rrreee此输出表明程序中存在 4 字节的内存泄漏,该泄漏来自函数 leak()
中未释放的 int
rrreee
int
yang belum dikeluarkan dalam fungsi leak()
. 🎜Atas ialah kandungan terperinci Bagaimana untuk menyahpepijat kebocoran memori C++ menggunakan Valgrind?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!