- //memleak.cpp
- #include<stdlib.h>
- #include<crtdbg.h>
- using namespace std;
- int main( void )
- {
- // REG_DEBUG_NEW; // +
- _CrtMemState s1, s2, s3; // 声明内存状态结构变量
- _CrtMemCheckpoint( &s1 );// 获取第一个内存状态快照
- // 在这里进行内存分配
- int* p = new int[2];
- p[0] = 'A';
- p[1] = 'B';
- //delete []p;
- _CrtMemCheckpoint( &s2 );// 获取第二个内存状态快照
- // 比较两个内存快照的差异
- if ( _CrtMemDifference( &s3, &s1, &s2) )
- _CrtMemDumpStatistics( &s3 );// dump 差异结果
- // 输出内存泄漏报告,显示在 Output 窗口的 Debug 页中
- _CrtDumpMemoryLeaks();
- cout << "--End--" << endl;
- return 0;
- /*
- REG_DEBUG_NEW; // +
- char* p = new char[2];
- cout << "--End--" << endl;
- return 0;
- */
- }
以上代码只有在DEBUG时,才能看到运行结果!