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 _CrtDumpMemoryLeaks()
does print memory leaks to the output window, but it does not show where it happens.
I've read the MSDN article at Memory Leak Detection Enabling , and it explains that if I define _CRTDBG_MAP_ALLOC
it should output the line number of the offending statement. This does not happen in my case. (I was however able to get it to work if I use malloc() directly -- not by using 'new').
The code:
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *var = new int(5);
_CrtDumpMemoryLeaks();
return 0;
}
The output is the following:
Detected memory leaks!
Dumping objects ->
{58} normal block at 0x007D1510, 4 bytes long.
Data: < > 05 00 00 00
Object dump complete.
If _CrtDumpMemoryLeaks()
is unable to output line numbers when allocating using 'new' then suggestions for other ways to achieve similar behavior is appreciated.
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'.
That's an old version of Visual Leak Detector.
Try this: http://vld.codeplex.com/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With