使用Visual调试库检测内存泄露

来源:互联网 发布:tensorflow 1.2 whl 编辑:程序博客网 时间:2024/05/29 11:03

#include <iostream>

using namespace std;

 

// 使用调试库

#define _CRTDBG_MAP_ALLOC

#include <cstdlib>

#include <crtdbg.h>

// 重定义new运算符

#ifdef _DEBUG

#ifndef DBG_NEW

#define DBG_NEW new (_NORMAL_BLOCK,__FILE__,__LINE__)

#define new DBG_NEW

#endif

#endif

 

class Simple{

public:

    Simple()

    {

         m_pInt = new int();

    }

    virtual ~Simple()

    {

         delete m_pInt;

    }

 

    void setIntPtr(intinInt)

    {

         *m_pInt = inInt;

    }

 

private:

    int* m_pInt;

};

 

void dosomething(Simple*&outSimple)

{

    outSimple = new Simple();

}

 

int _tmain(int argc,_TCHAR* argv[])

{

    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF |_CRTDBG_LEAK_CHECK_DF);

 

    Simple* pSimple = new Simple();

 

    // 这里导致内存泄露

    dosomething(pSimple);

 

    delete pSimple;

 

    return 0;

}


该程序有两处内存泄露:


Detected memory leaks!

Dumping objects ->

c:\users\administrator\documents\visual studio 2013\projects\cpptestpro\cpptestpro\cpptestpro.cpp(34) : {200} normal block at 0x0057E1C8, 4 bytes long.

 Data: <    > 00 00 00 00

c:\users\administrator\documents\visual studio 2013\projects\cpptestpro\cpptestpro\cpptestpro.cpp(61) : {199} normal block at 0x0057E180, 8 bytes long.

 Data: <X     W > 58 CA F1 00 C8 E1 57 00

Object dump complete.


0 0
原创粉丝点击