在使用MFC庫開發(fā)程序時(shí),我非常喜歡MFC框架中的內(nèi)存泄漏診斷機(jī)制,它的確能很好地幫助我們查找出內(nèi)存泄漏。可是鏈接了MFC庫也使得生成的可執(zhí)行文件大了許多,這個(gè)沒什么負(fù)面影響。最可怕的是如果僅為了使用內(nèi)存診斷機(jī)制,而帶來了鏈接庫沖突的麻煩。我也是在遇到這個(gè)問題時(shí),才寫出了一個(gè)簡易的內(nèi)存診斷機(jī)制。
在windows的SDK中有一套用于診斷內(nèi)存泄漏的機(jī)制,只是MFC封裝得更好,所以知名度不夠高。下面我封裝了CRT中的內(nèi)存泄漏診斷機(jī)制,用起來也比較方便,直接在stdafx.h中包含MyDebug.h, 在要用診斷機(jī)制的文件中加入如下的代碼。
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

/**//*
* @File: DebugNew.h
*
* @Author: Robert xiao
*
* @Created: 2012/11/04
*
* @Purpose:
*/

#pragma once

#define THIS_FILE __FILE__
void* __cdecl operator new(size_t nSize, int nType, const char* lpszFileName, int nLine);

#ifdef _DEBUG
void* _cdecl operator new(size_t nSize, const char* lpszFileName, int nLine);
void* __cdecl operator new[](size_t nSize, const char* lpszFileName, int nLine);
void __cdecl operator delete(void* p);
void __cdecl operator delete[](void* p);
#define DEBUG_NEW new(THIS_FILE, __LINE__)
#else
#define DEBUG_NEW new
#endif // _DEBUG

/**//*
* @File: DebugNew.cpp
*
* @Author: Robert xiao
*
* @Created: 2012/11/04
*
* @Purpose:
*
*/
#include "stdafx.h"
#include <crtdbg.h>
#include "MyDebug.h"

namespace


{
class AutoDetectMemory

{
public:
AutoDetectMemory()

{
#ifdef _DEBUG
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
}
};

static AutoDetectMemory gs_am;
}


void* _cdecl operator new(size_t nSize, const char* lpszFileName, int nLine)


{
return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);
}

void* __cdecl operator new[](size_t nSize, const char* lpszFileName, int nLine)


{
return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);
}

void __cdecl operator delete(void* p)


{
#if defined(_DEBUG)
_free_dbg(p, _NORMAL_BLOCK);
#else
free(p);
#endif
}

void __cdecl operator delete[](void* p)


{
::operator delete(p);
}

void* __cdecl operator new(size_t nSize, int nType, const char* lpszFileName, int nLine)


{
#ifndef _DEBUG
UNREFERENCED_PARAMETER(nType);
UNREFERENCED_PARAMETER(lpszFileName);
UNREFERENCED_PARAMETER(nLine);
return ::operator new(nSize);
#else
return _malloc_dbg(nSize, nType, lpszFileName, nLine);
#endif
}
