|
Visual C++ Debugging: memory leak 어떻게 관리할 것인가? Q: memory leak 이란 무엇인가?
Code: void foo() { int *i = new int; *i = 44; }
Code: { char* str = new char[20]; strcpy(str,"memory leak"); }
Code: class Sample { int* val; public: Sample() { val = new int; *val = 44; } ~Sample() { delete val; } }; void foo() { Sample* a = new Sample; Sample* b = new Sample; a = b; delete a; // 이때 b도 사실상 삭제되었다. //delete b; // 이미 삭제됨.
Code: double* d = new double[10]; delete d; // delete d[0]; // must use delete [] d;
Code: int *i; while(someCondition) { i = new int; // some code } delete i;
Code: Detected memory leaks! Dumping objects -> D:\VisualC++\CodeGuru\MemoryLeak\MemoryLeak.cpp(67) : {60} normal block at 0x00324818, 4 bytes long. Data: <, > 2C 00 00 00 Object dump complete.
Code: Detected memory leaks! Dumping objects -> {60} normal block at 0x00324818, 4 bytes long. Data: <, > 2C 00 00 00 Object dump complete.
'_CRTDBG_MAP_ALLOC'를 정의 하면, memory가 leak되는 곳의 file까지 보여준다. 파일이름에 추가로 따라오는 번호는 file 내부에 있는 line 번호이다. C++의 ‘new’와 ‘delete’에서 '_CRTDBG_MAP_ALLOC'를 사용했을때의 효과는 무엇인가? A: application에서 debug모드로 '_CRTDBG_MAP_ALLOC' flag를 정의 하면, heap function들의 기본 버전은 debug모드로 mapping된다. 이 flag는 '_DEBUG' flag가 정의되어 있을때만 사용 가능하다. 만약 '_CLIENT_BLOCK' 할당 형태로 사용하길 원한다면, 'CRTDBG_MAP_ALLOC'를 define 하지 마라. 대신에, 'net'의 Debug버전을 직접 호출하거나, 아래의 예에서 처럼 debug 모드에서의 'new'를 대치 할수 있는 macro를 만들어 써야 한다. 'delete'의 debug버전은 보든 block type들에서 동작하고 release 버전에서도 program의 수정이 필요하지 않다. // DbgNew.h // Defines global operator new to allocate from client blocks #ifdef _DEBUG #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__) #else #define DEBUG_CLIENTBLOCK #endif // MyApp.cpp // Compile options needed: /Zi /D_DEBUG /MLd or use a // Default Workspace for a Console Application to build a debug version #include <crtdbg.h> #include <dbgnew.h> #ifdef _DEBUG #define new DEBUG_CLIENTBLOCK #endif int main( ) { int* array = new int[10]; _CrtMemDumpAllObjectsSince(NULL); return 0; }
typedef struct _CrtMemState { struct _CrtMemBlockHeader* pBlockHeader;//최근 할당된 block을 위한 pointer unsigned long lSizes[_MAX_BLOCKS]; //할당된 각각의 block type들의 총 byte } _CrtMemState;
아래의 function들은 heap의 상태와 내용을 기록하고 memory leak과 다른 문제들을 감지하기 위해 정보들을 이용한다.
Code: _CrtMemState s1, s2, s3; _CrtMemCheckpoint( &s1 ); // memory allocations take place here _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2) ) _CrtMemDumpStatistics( &s3 );
Code: #include <iostream> #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> int main() { int* array = new int[10]; _CrtDumpMemoryLeaks(); return 0; }
Code: #ifdef _DEBUG CMemoryState oldMemState, newMemState, diffMemState; oldMemState.Checkpoint(); #endif // Do your memory allocations and deallocations. CSite* p = new CSite( "CodeGuru", "http://www.codeguru.com"); #ifdef _DEBUG newMemState.Checkpoint(); if( diffMemState.Difference( oldMemState, newMemState ) ) { TRACE( "Memory leaked!\n" ); } #endif
| ||||
Machine Vision & Image Processing
댓글
댓글 쓰기