본문 바로가기

3.구현/VC++

memory leak 자동 감지기

#ifndef __EMEMORY_H_20091125__
#define __EMEMORY_H_20091125__

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _USE_MEM_LEAK

#ifdef _WIN32
#include <stdlib.h>
#include <crtdbg.h>

#ifdef __cplusplus
	inline void* __cdecl operator new(size_t size, const char* filename, int line)
	{
		return ::operator new(size, 1, filename, line);
	}

	inline void __cdecl operator delete(void* ptr, const char* filename, int line)
	{
		::operator delete(ptr, _NORMAL_BLOCK, filename, line);
	}

#define new DEBUG_NEW
#define DEBUG_NEW new(THIS_FILE, __LINE__)

#endif // __cplusplus

#define DECLARE_THIS_FILE() static char THIS_FILE[] = __FILE__;

#define MALLOC_DBG(x) _malloc_dbg(x, 1, THIS_FILE, __LINE__);
#define CALLOC_DBG(x, s) _calloc_dbg(x, s, 1, THIS_FILE, __LINE__);
#define REALLOC_DBG(x, s) _realloc_dbg(x, s, 1, THIS_FILE, __LINE__);
#define RECALLOC_DBG(p, x) _recalloc_dbg(p, x, 1, THIS_FILE, __LINE__);

#ifdef malloc
#undef malloc
#endif
#define malloc(x) MALLOC_DBG(x)
#ifdef calloc
#undef calloc
#endif
#define calloc(x, s) CALLOC_DBG(x, s)
#ifdef realloc
#undef realloc
#endif
#define realloc(p, s) REALLOC_DBG(p, s)
#ifdef recalloc
#undef recalloc
#endif
#define recalloc(p, x) RECALLOC_DBG(p, x)

	// Send all reports to STDOUT
#define DBG_MEM_INIT() \
	{\
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );\
	_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );\
	_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );\
	_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );\
	_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );\
	_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );\
	}

#define DBG_MEM_FREE() \
	{\
	_CrtDumpMemoryLeaks();\
	}


#else //_WIN32

#define DECLARE_THIS_FILE()

#define DBG_MEM_INIT() {}

#define DBG_MEM_FREE() {}

#endif //_WIN32


#else //_USE_MEM_LEAK

#include <stdlib.h>
#include <memory.h>

#define DECLARE_THIS_FILE()

#define DBG_MEM_INIT() {}

#define DBG_MEM_FREE() {}

#endif //_USE_MEM_LEAK

#ifdef __cplusplus
}
#endif

#endif // __EMEMORY_H_20091125__

 

 

//usage
//각 소스파일에
DECLARE_THIS_FILE()

//main() 시작 위치에
DBG_MEM_INIT();

//main() 종료 위치에
DBG_MEM_FREE();

 

 

 

반응형