// MyMemoryState.h: interface for the CMyMemoryState class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MYMEMORYSTATE_H__F1EC6E7F_83E2_41BE_8C66_20BA020316FA__INCLUDED_) #define AFX_MYMEMORYSTATE_H__F1EC6E7F_83E2_41BE_8C66_20BA020316FA__INCLUDED_ #include <afx.h> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMyMemoryState { public: CMyMemoryState(); virtual ~CMyMemoryState(); private: CMemoryState MemoryStateBefore; CMemoryState MemoryStateAfter; CMemoryState MemoryStateDiffrent; }; #endif // !defined(AFX_MYMEMORYSTATE_H__F1EC6E7F_83E2_41BE_8C66_20BA020316FA__INCLUDED_) // MyMemoryState.cpp: implementation of the CMyMemoryState class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyMemoryState.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMyMemoryState::CMyMemoryState() { AfxEnableMemoryTracking(TRUE); MemoryStateBefore.Checkpoint(); } CMyMemoryState::~CMyMemoryState() { MemoryStateAfter.Checkpoint(); if(0 != MemoryStateDiffrent.Difference(MemoryStateBefore, MemoryStateAfter)) { MemoryStateDiffrent.DumpAllObjectsSince(); //有内存泄漏: 响3声报警音 Beep(200, 200); Beep(200, 200); Beep(200, 200); } } //手工添加MFC程序的内存泄漏检测代码 #include "stdafx.h" #include <windows.h> #include <crtdbg.h> #include <stdlib.h> #include <stdio.h> //内存泄漏调试好了就去掉, //#include "MyMemoryState.h" //必须把调试宏放在这, 才能显示出内存泄漏的具体行号. /** #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif */ int fnMemoryLeakTest(); //static CMyMemoryState g_MyMemoryState; int main(int argc, char* argv[]) { fnMemoryLeakTest(); return 0; } int fnMemoryLeakTest() { int nLenMsg = 1024; PCHAR pcMsg = new CHAR[nLenMsg]; memset(pcMsg, 0, nLenMsg); strcpy(pcMsg, "Memory Leak's demo/n"); printf("%s/n", pcMsg); //在非MFC程序的Debug模式下, pcMsg 没有被回收, 内存泄漏了 //但是直到退出main(), 在调试模式下,也看不到任何的内存泄漏提示! return S_OK; } //实验总结 /** 原来这个程序是非MFC程序. 有了内存泄漏在调试环境IDE也显示不出来 project>>Setting>>General 检测泄漏时: Microsoft Foundation Classes: Use MFC in a Shared Dll 不检测泄漏时: Not Using MFC #include "MyMemoryState.h", 使这个程序变成了mfc程序. 这样可以在调试环境IDE下, 当程序运行完, 可以看出内存泄漏. 把内存泄漏修正后, 程序又变成了非MFC程序. 编译时,把通不过的有关于MyMemoryState的代码注释掉, 并把MyMemoryState的2个实现文件"Exclude file from build" 大型的非MFC程序,这么搞,好像编译不过. 特别是带第三方静态库的程序 from codeproject, 是解决内存泄漏的一种思路 没有实用价值, 只是演示手工添加MFC的内存泄漏检测代码. */