Finding memory leaks

I recently came across something
that I found to be a major improvement in my ability to program in MS
Developer Studio version 5. It concerns memory leaks.
When running the Debugger, if you have the Dump function on, you get a list
of objects that did not get deallocated. These are defined as ‘Memory
Leaks’.

If we allocate memory for a character array in a function:

void MyFunction(void)
{
	char * MyCharArray = new char[10];
	.
	.
	.
	//delete [ ]MyCharArray;
}

but we don’t free it, running the program will produce the message:

Detected memory leaks!
Dumping objects ->
C:vcpp32myprojecttest.cpp(62) : {39} normal block at 0x00780DF0, 10 bytes
long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD
Object dump complete.

Now in this case, it gave us the CPP file and line number, but often it does
not. One way to find the leak would be to put a breakpoint in memory at the
memory address used by the allocation (assuming it’s constant).

But there’s a better way!

The number in the curly brackets, is an allocation number. Each allocation
receives a serial number. When you get a leak, you can use this number to
automatically place a breakpoint at the point in the program where the
allocation is being made. To do this, you can do one of two things.

1. Add a call to the function _CrtSetBreakAlloc(), giving it the number in
the curly brackets.

2. In the debugger, set the value of the variable _crtBreakAlloc to that
number.

You want to do this as early in the program as possible. The effect of doing
that is a breakpoint on the line of the allocation of the ‘new’ function.
You then use the call stack to find the exact place in the program that
called the allocation.

(See MSDN article Q151585 for more information)

More by Author

Must Read