Memory State Comparison
This topic applies to:
Pro and Team
Does not apply
Command or commands hidden by default.
Another technique for locating memory leaks involves taking snapshots of the application's memory state at key points. The CRT library provides a structure type, _CrtMemState, which you can use to store a snapshot of the memory state:
_CrtMemState s1, s2, s3;
To take a snapshot of the memory state at a given point, pass a _CrtMemState structure to the _CrtMemCheckpoint function. This function fills in the structure with a snapshot of the current memory state:
_CrtMemCheckpoint( &s1 );
You can dump the contents of a _CrtMemState structure at any point by passing the structure to the _CrtMemDumpStatistics function:
_CrtMemDumpStatistics( &s1 );
This function prints a dump of memory allocation information that looks like this:
0 bytes in 0 Free Blocks. 0 bytes in 0 Normal Blocks. 3071 bytes in 16 CRT Blocks. 0 bytes in 0 Ignore Blocks. 0 bytes in 0 Client Blocks. Largest number used: 3071 bytes. Total allocations: 3764 bytes.
To determine whether a memory leak has occurred in a section of code, you can take snapshots of the memory state before and after the section, and then use _CrtMemDifference to compare the two states:
_CrtMemCheckpoint( &s1 ); // memory allocations take place here _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2) ) _CrtMemDumpStatistics( &s3 );
As the name implies, _CrtMemDifference compares two memory states (s1 and s2) and produces a result (s3) that is the difference of the two states. Placing _CrtMemCheckpoint calls at the beginning and end of your program and using _CrtMemDifference to compare the results provides another way to check for memory leaks. If a leak is detected, you can use _CrtMemCheckpoint calls to divide your program and locate the leak using binary search technique.