VC++ Debug 執行期庫內建記憶體配置追蹤,程式結束時自動報告未釋放的 `new`/`malloc` 區塊,並標示配置原始碼檔案與行號 (需 `DEBUG_NEW`)。本文說明啟用方式、輸出解讀、常見洩漏模式與釋放策略。
在專案 `stdafx.h` 或主檔案最前端加入:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
Detected memory leaks!
Dumping objects ->
d:\proj\test.cpp(42) : {36} normal block at 0x00770520, 4 bytes long.
Data: < w > EC 02 77 00
d:\proj\test.cpp(41) : {35} normal block at 0x00770320, 100 bytes long.
Data: < > CD CD CD CD ...
{34} normal block at 0x007703B0, 200 bytes long.
Data: < > CD CD CD CD ...
Object dump complete.
| 函數 | 用途 |
|---|---|
| `_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF)` | 啟用配置追蹤與結束時自動檢查 (預設已開啟) |
| `_CrtSetBreakAlloc(lAllocNum)` | 在指定區塊編號配置時中斷 |
| `_CrtMemCheckpoint(&state)` | 記錄當前記憶體狀態快照 |
| `_CrtMemDifference(&diff, &old, &new)` | 比較兩快照差異 |
| `_CrtDumpMemoryLeaks()` | 手動觸發洩漏報告 |
| `_CrtDoForAllClientObjects(fn, ctx)` | 枚舉所有用戶區塊呼叫回呼 |
Detected memory leaks!