3

I have a memory leak that I'm trying to hunt down in my mfc program. Typically I would do something like the following:

header file

// Leak Detection
#if defined(WIN32) && defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
#endif

cpp file

// Leak detection
#if defined(WIN32) && defined(_DEBUG) && defined(_CRTDBG_MAP_ALLOC)
    #ifdef DEBUG_NEW 
        #undef DEBUG_NEW
    #endif
    #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
    #define new DEBUG_NEW
#endif

This technique works well in most files, but when I include it in some files such as my document, I get the error: error C2661: 'CObject::operator new' : no overloaded function takes 4 arguments

What's the solution here? Should I be #undef-ing new somewhere or something?

Thanks!

Jordan
  • 9,014
  • 8
  • 37
  • 47
  • Pedantically speaking `#define new DEBUG_NEW` invokes undefined behavior (if I correctly recall). – Nawaz Jun 08 '12 at 16:35
  • @Nawaz: It seems to work fine for other classes. What would be the proper way to detect where the memory leak actually occurs? This seems like it's the "Microsoft recommended solution". Most profilers do funny things with my code. – Jordan Jun 08 '12 at 16:39
  • The correct way to do this is to replace new and delete operators for your class or globally. – Alok Save Jun 08 '12 at 16:39
  • @Jordan: Hope this helps: [How should I write ISO C++ Standard conformant custom new and delete operators?](http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators) – Alok Save Jun 08 '12 at 16:40
  • 1
    @Als: A lot of that went a bit over my head. Is there an example of code I should use in this situation? Where would I implement the custom new handler in an mfc application? – Jordan Jun 08 '12 at 16:49

2 Answers2

1

I also use the same functionality as you for the purpose of leak detection.

Either you can comment out or delete the DEBUG_NEW definition block, assuming you don't need it any more for trapping memory leaks. Or if you still need it, leave it as it is and use

#ifdef _DEBUG
#undef new
    CMyOject* pMyObjectInst = new CMyObject();
#define new DBG_NEW
#endif  

So, you undefine new just before object creation (see the line numbers in your Error List) and redefine it again immediately after, so that any memory leaks which occur after this object creation are still identifiable.

Glenn Sallis
  • 415
  • 3
  • 11
1

I have similar problem caused by putting #define new DEBUG_NEW before #include ... statements in .cpp file. Changing the order resolved my problem.

Ciborek
  • 11
  • 1