#define _CRTDBG_MAP_ALLOC // 必須最前,映射 malloc/free 至 _malloc_dbg/_free_dbg
#include
#include // 定義 _CrtDumpMemoryLeaks 等
僅在 _DEBUG 定義時生效 (Debug 版)。Release 版不受影響。
// 程式結束前手動呼叫
_CrtDumpMemoryLeaks();
輸出範例:
Detected memory leaks!
Dumping objects ->
{145} normal block at 0x00A4B8C0, 64 bytes long.
Data: < CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD >
Object dump complete.
若定義 _CRTDBG_MAP_ALLOC,輸出額外包含 **檔案名與行號**:leaktest.cpp(20)。
// 程式進入點 (如 CWinApp::InitInstance) 最早處
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
程式正常退出時自動呼叫 _CrtDumpMemoryLeaks。適用多出口程式。
| 功能 | API | 說明 |
|---|---|---|
| 設定斷點於特定配置序號 | _CrtSetBreakAlloc(145) | 配合輸出的 {145} 斷點進入該配置點 |
| 標記記憶體區塊 | _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF) | 每次配置/釋放檢查堆完整性 (極慢) |
| 改變報告輸出目的地 | _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE) + _CrtSetReportFile(_CRT_ERROR, hFile) | 導向檔案而非輸出視窗 |
| 檢查特定指標狀態 | _CrtIsMemoryBlock(ptr, size, &reqNum, &filename, &lineno) | 取得配置序號、來源檔案行號 |
| 記憶體狀態統計 | _CrtMemCheckpoint(&state), _CrtMemDifference, _CrtMemDumpStatistics | 比較兩時間點記憶體狀態 |
_CRTDBG_MAP_ALLOC 必須在 stdlib.h **之前**,crtdbg.h **之後**。crtdbg.h 已將 new/delete 映射至 _malloc_dbg/_free_dbg,**可檢測**。stdafx.h 頂端加入三行啟用代碼。CWinApp::InitInstance 首行加 _CrtSetDbgFlag(...) 自動檢測。/heapcheck:145 (或代碼 _CrtSetBreakAlloc(145)) 重跑偵錯。new 是否有配對 delete。