본문 바로가기
C, C++

메모리 누수 간단 검사 방법

by 오징어땅콩2 2025. 9. 4.
반응형
#if defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC // 디버그 할당을 사용하겠다는 선언
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__) // 덤프를 좀 더 쉽게 보기 위한 것
#endif

// Memory block identification
// #define _FREE_BLOCK      0
// #define _NORMAL_BLOCK    1
// #define _CRT_BLOCK       2
// #define _IGNORE_BLOCK    3
// #define _CLIENT_BLOCK    4
// #define _MAX_BLOCKS      5
// 다른 건 별로 의미 없고 _NORMAL_BLOCK과 _CLIENT_BLOCK만 알면됨

#include <crtdbg.h> // 디버그 메모리 추적을 위한 헤더 파일
#include <cstdlib>  // system()을 위한 헤더 파일

int main()
{
#if defined(DEBUG)
        // 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
        // 다른 건 별로 의미 없고 _CRTDBG_ALLOC_MEM_DF와 _CRTDBG_LEAK_CHECK_DF만 알면됨.
        // DF는 Debug Flag의 약자
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

	int* a = new int; // 메모리 누수 테스트 코드(실제로는 이렇게 하면 안됨 ㄷㄷ)

	system("pause");
	return 0;
}

'C, C++' 카테고리의 다른 글

C/C++ dll 파이썬에서 호출 하기-#2  (0) 2025.02.28
C/C++ dll 파이썬에서 호출 하기  (0) 2025.02.27
가끔 사용하는 코딩 #1  (0) 2024.10.10
코딩 이야기 #1  (0) 2020.07.22

댓글