Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Valgrind 偵測 C 程式七大記憶體錯誤:洩漏、越界、雙重釋放、野指標實戰代碼

編輯:關於 Linux

測試程式涵蓋錯誤類型

  1. 動態記憶體洩漏(malloc 未 free)
  2. 資源洩漏(fopen 未 fclose)
  3. malloc 越界寫入
  4. 陣列越界(strcpy 複製過長字串)
  5. 雙重 free
  6. 使用野指標(未初始化指標)
  7. 釋放野指標

編譯與執行

gcc -g test.c -o test
valgrind --leak-check=full ./test

Valgrind 會逐一報告上述七類錯誤位置與堆疊。

注意

  • 僅能偵測「實際執行到」的程式碼路徑。
  • 野指標若導致即時 crash,Valgrind 可能來不及報告;大型專案中野指標不一定會 crash,故仍具偵測價值。

結語

編寫涵蓋七大經典錯誤的測試案例,配合 valgrind --leak-check=full,即可建立記憶體錯誤偵測基準,守護 C/C++ 專案品質。

Copyright © Windows教程網 All Rights Reserved