具体地讲检查内存漏洞需要以下几个步骤: 在你所检测的程序段的开始处建立一个CmemoryState对象,调用其成员函数Checkpoint,以取得当前内存使用情况的快照; 在你所检测的程序段的末尾处再建立一个CmemoryState 对象,调用其成员函数Checkpoint ,以取得当前内存使用情况的快照; 再建立第三个CmemoryState 对象,调用其成员函数Difference,把第一个CmemoryState对象和第二个CmemeoryState对象作为其参数.,如果两次内存快照不相同,则该函数返回非零,说明此程序 段中有内存漏洞。下面我们来看一个典型的例子: // 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

评论