這個主題適用於:
版本 |
Visual Basic |
C# |
F# |
C++ |
Web Developer |
|---|---|---|---|---|---|
Express |
![]() |
![]() |
![]() |
僅適用原生 |
![]() |
Pro、Premium 和 Ultimate |
![]() |
![]() |
![]() |
僅適用原生 |
![]() |
注意事項 |
|---|
根據您目前使用的設定或版本,您所看到的對話方塊與功能表指令可能會與 [說明] 中描述的不同。 若要變更設定,請從 [工具] 功能表中選取 [匯入和匯出設定]。 如需詳細資訊,請參閱 使用設定。 |
本主題說明如何執行記憶體的快照來幫助尋找記憶體遺漏。
若要偵測記憶體遺漏
建立 CMemoryState Members 物件並且呼叫 CMemoryState::Checkpoint 成員函式。 這會建立第一個記憶體快照。
程式執行記憶體配置和解除配置操作之後,會建立另一個 CMemoryState 物件並且呼叫此物件的 Checkpoint。 這會取得記憶體使用的第二個快照。
建立第三個 CMemoryState 物件並且呼叫 CMemoryState::Difference 成員函式,會提供兩個先前的 CMemoryState 物件來當做引數。 如果兩種記憶體狀態之間有差異,Difference 函式會傳回非零值。 這表示有些記憶體區塊沒有解除配置。
這個範例會顯示程式碼看起來的樣子:
// Declare the variables needed #ifdef _DEBUG CMemoryState oldMemState, newMemState, diffMemState; oldMemState.Checkpoint(); #endif // Do your memory allocations and deallocations. CString s("This is a frame variable"); // The next object is a heap object. CPerson* p = new CPerson( "Smith", "Alan", "581-0215" ); #ifdef _DEBUG newMemState.Checkpoint(); if( diffMemState.Difference( oldMemState, newMemState ) ) { TRACE( "Memory leaked!\n" ); } #endif請注意記憶體檢查陳述式由 #ifdef _DEBUG / #endif 區塊括號起來,因此它們只會在程式的 Win32 偵錯版本中編譯。
現在您知道有記憶體遺漏存在,您可以使用另一個成員函式,CMemoryState::DumpStatistics,來記憶體統計資料檢視,幫助您尋找遺漏記憶體。
.gif)
注意事項