一段检测内存泄漏的代码
2005年9月30日1:18分
我的一个游戏服务器程序中的内存泄漏的问题终于搞定了.
我把这段代码贴出来了.
主要是怕自己找不到.
把下面的代码命名为debug.h
然后用
#include "debug.h"
就搞定了!在你的代码中不需要添加任何代码.
#ifndef _DEBUG_NEW_H_
#define _DEBUG_NEW_H_
#ifdef _DEBUG
#ifdef new
#undef new
#endif
#define CRTDBG_MAP_ALLOC
#include
#include
#include
namespace __impl {
class CCriticalSection {
public:
CCriticalSection() { ::InitializeCriticalSection( &m_cs ); }
~CCriticalSection() { ::DeleteCriticalSection( &m_cs ); }
void Enter() { ::EnterCriticalSection( &m_cs ); }
void Leave() { ::LeaveCriticalSection( &m_cs ); }
private:
CRITICAL_SECTION m_cs;
};
class CDumbCS {
public:
void Enter() { }
void Leave() { }
};
class CGuard {
public:
#ifdef _MT
typedef CCriticalSection lock_type;
#else
typedef CDumbCS lock_type;
#endif
static lock_type* GetLock() {
static lock_type lock;
return &lock;
}
public:
CGuard() { GetLock()->Enter(); }
~CGuard() { GetLock()->Leave(); }
};
class CDebugEnv {
public:
CDebugEnv() {
::_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
}
};
}
// normal
inline
void* __cdecl operator new( size_t nSize, const char* lpszFileName, int nLine )
{
static __impl::CDebugEnv __dbgEnv;
__impl::CGuard guard;
return ::_malloc_dbg( nSize, _NORMAL_BLOCK, lpszFileName, nLine );
}
// 当"new表达式调用的构造函数抛出异常"时可以正确地释放内存
inline
void __cdecl operator delete( void* p, const char* /*lpszFileName*/, int /*nLine*/ )
{
__impl::CGuard guard;
::_free_dbg( p, _NORMAL_BLOCK );
}
// normal
inline
void __cdecl operator delete( void* p)
{
__impl::CGuard guard;
::_free_dbg( p, _NORMAL_BLOCK );
}
#define new new(__FILE__, __LINE__)
#endif // _DEBUG
#endif

浙公网安备 33010602011771号