如何使用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中文網其他相關文章!