vs 2017/2015/2013 如何定位C++内存泄漏

定位内存泄漏是C++的一个大问题

我们可以通过如下方式进行定位:

//在主函数文件中加入如下代码

#include <stdlib.h>  
#include <crtdbg.h>  
  
  
#ifdef _DEBUG  
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)  
#endif  
  
void EnableMemLeakCheck()  
{  
    int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);  
    tmpFlag |= _CRTDBG_LEAK_CHECK_DF;  
    _CrtSetDbgFlag(tmpFlag);  
}  
  
using namespace std;  
int main()  
{  
    EnableMemLeakCheck();  
    //_CrtSetBreakAlloc(这里有第一遍注释掉, 第二遍再执行);  
        自己的代码  
}  

在 debug 模式下,可以看到如下信息:

 此时我们注意大括号的内容,这就是可以我们的程序内存泄漏的地方。

将上面注释掉的代码加入,并将大括号的数字填入,就可以让程序停在内存泄漏的地方。

如下,这里我们让程序停在 556 处

//在主函数文件中加入如下代码

#include <stdlib.h>  
#include <crtdbg.h>  
  
  
#ifdef _DEBUG  
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)  
#endif  
  
void EnableMemLeakCheck()  
{  
    int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);  
    tmpFlag |= _CRTDBG_LEAK_CHECK_DF;  
    _CrtSetDbgFlag(tmpFlag);  
}  
  
using namespace std;  
int main()  
{  
    EnableMemLeakCheck();  
    //_CrtSetBreakAlloc(556);  
        自己的代码  
}  

参考:http://blog.csdn.net/dyx810601/article/details/52092835

posted @ 2017-05-28 21:13  仰望高端玩家的小清新  阅读(7350)  评论(0编辑  收藏  举报