[C++] 메모리 릭검사 CrtCheckMemory

2011. 6. 4. 08:46C++

http://shinobi.tistory.com/entry/CrtDumpMemoryLeaks

메모리 릭 검사
관련 헤더 - #include <crtdbg.h>


관련 함수

 _CRTIMP int __cdecl _CrtCheckMemory( void );
 /*
 * Bit values for _crtDbgFlag flag:
 *
 * These bitflags control debug heap behavior.
 */

#define _CRTDBG_ALLOC_MEM_DF        0x01  /* Turn on debug allocation */
#define _CRTDBG_DELAY_FREE_MEM_DF   0x02  /* Don't actually free memory */
#define _CRTDBG_CHECK_ALWAYS_DF     0x04  /* Check heap every alloc/dealloc */
#define _CRTDBG_RESERVED_DF         0x08  /* Reserved - do not use */
#define _CRTDBG_CHECK_CRT_DF        0x10  /* Leak check/diff CRT blocks */
#define _CRTDBG_LEAK_CHECK_DF       0x20  /* Leak check at program exit */


 _CRTIMP long __cdecl _CrtSetBreakAlloc( _In_ long _BreakAlloc );
 BreakAlloc 주소를 넣어주면 해당 메모리 생성시에 그 위치에 브레이크 포인트를 걸어줍니다.

 _CRTIMP int __cdecl _CrtDumpMemoryLeaks( void );
 모든 함수가 종료된 시점 마지막에 추가해주면 해지 되지 않은 메모리를 알려준다.

예제)
#include <crtdbg.h>
#include <stdlib.h>
#include <windows.h>

void main()
{
     _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
     //_CrtSetBreakAlloc(24534);
     // 동적 메모리 할당
     int nValue = new int;
     // 메모리 삭제
     //delete(nValue);
     _CrtDumpMemoryLeaks();
}

Detected memory leaks
Dumping object
{24534} nomal block at 0x01BC13D7, 4bytes int.
Data: < > 08 00 00 00 00 00 00 00

위에 같이 메모리 릭이 발생한 경우 소스 코드에 _CrtSetBreakAlloc(24534); 추가하면 메모리 릭이 발생한 위치에 브레이크 포인트가 걸린다.



CrtSetBreakAlloc 대신 Visual Studio 를 이용해 Break Point 걸기


Detected memory leaks!
Dumping objects ->
{198} normal block at 0x00608950, 5 bytes long.
 Data: <test > 74 65 73 74 00
Object dump complete.
Detected memory leaks!
Dumping objects ->
{207} normal block at 0x00608998, 4 bytes long.
 Data: <    > CD CD CD CD
{198} normal block at 0x00608950, 5 bytes long.
 Data: <test > 74 65 73 74 00
Object dump complete.
Detected memory leaks!
Dumping objects ->
{207} normal block at 0x00608998, 4 bytes long.
 Data: <    > CD CD CD CD
Object dump complete.


디버그/새중단점/ 중단점 추가를 이용해 해당 주소 위치에서 Break를 걸수 있습니다.
해제는 반드시 모든 중단점 제거를 통해 없애야 한다.