MemoryLeak.h
#ifndef _MEMORYLEAK_H_
#define _MEMORYLEAK_H_
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
static class MemoryMng
{
public:
MemoryMng() {
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
}
~MemoryMng() {
_ASSERTE( _CrtCheckMemory( ) );
}
} MemoryLeak;
#endif // _DEBUG
#endif // _MEMORYLEAK_H_
CrtDbgRoutine.cpp
#include "stdafx.h"
#include "MemoryLeak.h"
int _tmain(int argc, _TCHAR* argv[])
{
_CrtMemState ms;
for(int i = 0; i < 100; ++i)
{
int* p = new int;
}
//_CrtSetBreakAlloc(202); // 힙에 202번째로 메모리 할당을 요청하는 코드에서 브레이크
_CrtMemCheckpoint(&ms); // ms에 메모리 상태 저장
for(int i = 0; i < 200; ++i)
{
int* p = new int;
}
_CrtMemDumpAllObjectsSince(&ms); // ms에 저장된 메모리와 비교해서 누수된 메모리 리포트
_CrtDbgBreak();
return 0;
}
_CrtMemCheckpoint() 함수부터 _CrtMemDumpAllObjectsSince() 함수가 있는 부분까지 누수된 부분이 다음과 같이 표시된다.
.................................................................
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {209} normal block at 0x00375D90, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {208} normal block at 0x00375D50, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {207} normal block at 0x00375D10, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {206} normal block at 0x00375CD0, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {205} normal block at 0x00375C90, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {204} normal block at 0x00375C50, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {203} normal block at 0x00375C10, 4 bytes long.
Data: < > CD CD CD CD
d:\work\ogre\crtdbgroutine\crtdbgroutine.cpp(22) : {202} normal block at 0x00375BD0, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.
CrtDbgRoutine.exe이(가) 중단점을 트리거했습니다.
위의 누수된 부분을 더블클릭하면 그 코드로 이동한다.
'Programming > C++ 일반' 카테고리의 다른 글
#pragma init_seg( {compiler | lib | user | "섹션이름"[, 함수이름]} ) (0) | 2011.06.07 |
---|---|
클래스 멤버 함수의 함수 포인터 사용 (1) | 2011.02.11 |