C++ - Memory leak testing with _CrtDumpMemoryLeaks() - Does not output line numbers

前端 未结 5 1948
迷失自我
迷失自我 2020-12-10 03:15

I\'m working on a game with SDL in Visual Studio 2010. I came across the _CrtDumpMemoryLeaks() macro and thought I\'d give it a go. Invoking _CrtDumpMemor

相关标签:
5条回答
  • 2020-12-10 03:18

    Check out the piece of code.

    Overloading operator new and operator delete to log all memory allocations and deallocations

    I identified my memory leaks using this method.

    0 讨论(0)
  • 2020-12-10 03:22

    That's an old version of Visual Leak Detector.

    Try this: http://vld.codeplex.com/

    0 讨论(0)
  • 2020-12-10 03:24

    The accepted answer by Charles Bailey requires that you change your source code and this is not necessary. If you are using new and delete (or the array versions), all you need to do is place this code snippet in the stdafx.h file of each of your projects (including any static or dynamic library dependencies), and it will then give a source file and line number attached to each leaked memory object:

    #ifdef _DEBUG
       #ifndef DBG_NEW
          #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
          #define new DBG_NEW
       #endif
    #endif  // _DEBUG
    

    This comes straight from Microsoft's webpage on the matter.

    0 讨论(0)
  • 2020-12-10 03:28

    When you define _DEBUG and include <crtdbg.h> you get an overloaded operator new which takes additional parameters which you can use to specify the file and line numbers in placement new expressions.

    E.g.

    int* p = new (_NORMAL_BLOCK, __FILE__, __LINE__) int(5);
    

    You can wrap this in a conditionally defined macro, e.g.

    #ifdef _DEBUG
    #define DEBUG_NEW_PLACEMENT (_NORMAL_BLOCK, __FILE__, __LINE__)
    #else
    #define DEBUG_NEW_PLACEMENT
    #endif
    
    int* p = new DEBUG_NEW_PLACEMENT int(5);
    

    While you do see people defining a macro new to completely hide this form client code, I do not personally recommend it as it breaks anything already intentionally using placement new and you have to make sure that any headers using placement new (such as many standard headers) are included before any header redefining new. This can make it easy to let some inline uses of new in header files slip through without being 'adjusted'.

    0 讨论(0)
  • 2020-12-10 03:33

    You might need these defines after your includes

    
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif
    
    0 讨论(0)
提交回复
热议问题