The following instructions and examples will show you how to detect a memory leak.
·To detect a memory leak:
1.Create a CMemoryState object and call the Checkpoint member function to get the initial snapshot of memory.
2.After you perform the memory allocation and deallocation operations, create another CMemoryState object and call Checkpoint for that object to get a current snapshot of memory usage.
3.Create a third CMemoryState object and call the Difference member function, and supply the previous two CMemoryState objects as arguments. The Difference function will return TRUE if there is any difference between the two specified memory states, indicating that some memory blocks that have not been deallocated.
The following example shows how to check for memory leaks:
// Declare the variables needed
#ifdef _DEBUG
CMemoryState oldMemState, newMemState, diffMemState;
#endif
#ifdef _DEBUG
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 only compiled in debug versions of your program.