How To Find Memory Leaks With The Debugger

Visual studio debugger is a wonderful invention. See how it can show memory leaks (memory not properly de allocated) on exiting a program.


#include "afx.h"

// To show the memory leaks on exit
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

int main()
{ 
   char* str = new char[10];  // This won't be deallocated
   return 0;
}

See the following screen shot.

If DEBUG_NEW (defined in afx.h) is used, memory will be allocated in on a memory tracking basis (in the debug version).

You have to declare the above block in each file you need memory tracking.

Some Background Info

VC++ debugger defines some magic values for each type of memory location allocated.

0XCDCDCDCD – Memory allocated in heap, but not initialized

0xDDDDDDDD – Heap memory released

0xFDFDFDFD – Specifies the boundary of heap memory. It should not be overwritten as it designated the end.

0XCCCCCCCC – Memory allocated in stack, but not initialized.

Advertisements

One Response to How To Find Memory Leaks With The Debugger

  1. Yaroslav says:

    A lot of thx, was looking for that for a long time;)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: