VC下调试内存泄漏的办法

VC的控制台程序不会跟踪内存泄漏,如果需要调试控制台程序的内存情况,需要_CrtSetDbgFlag

详细原理我也不太懂,我也是从网上摘过来的,直接帖代码

// 内存泄漏跟踪
#ifdef WIN32
 #include <SDKDDKVer.h>
 #ifdef _DEBUG
  #define _CRTDBG_MAP_ALLOC
  #include <stdlib.h>
  #include <crtdbg.h>
  #define VC_MemLeakCheck() _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF)
  #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  //_CrtSetBreakAlloc(107); 跟踪内存泄漏块
 #else
  #define VC_MemLeakCheck()
 #endif // _DEBUG
#else
 #define VC_MemLeakCheck()
#endif // WIN32

在程序main入口处加入 VC_MemLeakCheck() 定义就可以了

int _tmain(int argc, _TCHAR* argv[])
{
    VC_MemLeakCheck();
    char * pnew = new char[1024];
    char * pmalloc = (char*)malloc(1024);
    return 0;
}

程序退出的时候会自动输出内存泄漏的情况

Detected memory leaks!
Dumping objects ->
e:	rytryjpegjpegtestjpegtest.cpp(15) : {108} normal block at 0x001137F8, 1024 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
e:	rytryjpegjpegtestjpegtest.cpp(14) : {107} normal block at 0x001133B8, 1024 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.
程序“[5452] jpegtest.exe: 本机”已退出,返回值为 0 (0x0)。
原文地址:https://www.cnblogs.com/cppboy/p/3732564.html