How to: Take Memory Snapshots
This topic applies to:
Edition |
Visual Basic |
C# |
C++ |
Web Developer |
---|---|---|---|---|
Express |
Native only |
|||
Standard |
Native only |
|||
Pro and Team |
Native only |
Table legend:
Applies |
|
Does not apply |
|
Command or commands hidden by default. |
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.
This topic shows how to take snapshots of memory to help locate a memory leak.
To detect a memory leak
Create a CMemoryState Members object and call the CMemoryState::Checkpoint member function. This creates the first memory snapshot.
After your program performs its memory allocation and deallocation operations, create another CMemoryState object and call Checkpoint for that object. This gets a second snapshot of memory usage.
Create a third CMemoryState object and call its CMemoryState::Difference member function, supplying as arguments the two previous CMemoryState objects. If there is a difference between the two memory states, the Difference function returns a nonzero value. This indicates that some memory blocks have not been deallocated.
This example shows what the code looks like:
// 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
Notice that the memory-checking statements are bracketed by #ifdef _DEBUG / #endif blocks so that they are compiled only in Win32 Debug versions of your program.
Now that you know a memory leak exists, you can use another member function, CMemoryState::DumpStatistics, to Memory Statistic Viewing that will help you locate it.