检测内存泄漏

1. 检测有无内存泄漏,可以在代码后添加_CrtDumpMemoryLeaks(),也可使用_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF)在代码的任意地方

添加后再output窗口可输出泄漏信息。

#include <crtdbg.h>

void leak()
{
    int* piBuf = new int();

    //delete piBuf;
    _CrtDumpMemoryLeaks();
}

int main()
{
    //_CrtSetBreakAlloc(73);

    leak();
    return 0;
}

 

如下:

Detected memory leaks!
Dumping objects ->
{73} normal block at 0x0000007EB0D444F0, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.

在VS2010以后的版本中,必须在出现泄漏代码之后添加_CrtDumpMemoryLeaks,否则无法输出内存泄漏信息,这也为查找内存泄漏提供了一种方式。而_CrtSetDbgFlag则可放在代码的任意地方。

 

2. 如果想知道内存泄漏在哪里,可以在代码中添加:

#ifdef _DEBUG
#define New new(_NORMAL_BLOCK, __FILE__, __LINE__)
#else
#define New new
#endif

在new的时候,使用New关键字;

#ifdef _DEBUG  
#define New   new(_NORMAL_BLOCK, __FILE__, __LINE__)  
#else
#define New      new
#endif  

#include <crtdbg.h>

void leak()
{
    int* piBuf = New int();

    //delete piBuf;
    _CrtDumpMemoryLeaks();
}

int main()
{
    //_CrtSetBreakAlloc(73);

    leak();
    return 0;
}

 

之后再output窗口会出现如下信息:

Detected memory leaks!
Dumping objects ->
xxx\consoletest\main.cpp(11) : {73} normal block at 0x00000062033344F0, 4 bytes long.
Data: < > 00 00 00 00
Object dump complete.

清楚的指定了main.cpp的第11行出现内存泄漏。

 

3. 泄漏信息中{}中的数字,表示当前的new在程序中第几次new操作,可使用_CrtSetBreakAlloc(73)让程序运行到第73次内存分配时,自动停下来,进入调试状态,如此可便利的进行内存泄漏调试。

 

#ifdef _DEBUG 
#define New new(_NORMAL_BLOCK, __FILE__, __LINE__) 
#else
#define New    new
#endif

#include <crtdbg.h>

void leak()
{
int* piBuf = New int();

//delete piBuf;
_CrtDumpMemoryLeaks();
}

int main()
{
_CrtSetBreakAlloc(73);

leak();
return 0;
}

 

posted @ 2018-02-25 14:41  谁说我是二师兄  阅读(208)  评论(0编辑  收藏  举报