Game Development Reference
In-Depth Information
The C-Runtime debug heap also provides many functions to help you examine the
heap for problems. I
'
ll tell you about three of them, and you can hunt for the rest
in the Visual Studio help files or MSDN.
n
_CrtSetDbgFlag(int newFlag)
: Sets the behavior of the debug heap.
n
_CrtCheckMemory(void)
: Runs a check on the debug heap.
n
_CrtDumpMemoryLeaks(void)
: Reports any leaks to
stdout
.
Here
'
s an example of how to put these functions into practice:
#include <crtdbg.h>
#if defined _DEBUG
#define GCC_NEW new(_NORMAL_BLOCK,__FILE__, __LINE__)
#endif
int main()
{
// get the current flags
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
// don
t actually free the blocks
tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
'
// perform memory check for each alloc/dealloc
tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
_CrtSetDbgFlag(tmpDbgFlag);
char *gonnaTrash = GCC_NEW char[15];
_CrtCheckMemory();
// everything is fine....
strcpy(gonnaTrash,
“
Trash my memory!
”
); // overwrite the buffer
_CrtCheckMemory();
// everything is NOT fine!
delete gonnaTrash;
// This brings up a dialog box too
…
char *gonnaLeak = GCC_NEW char[100]; // Prepare to leak!
_CrtDumpMemoryLeaks();
// Reports leaks to stderr
return 0;
}
Notice that the
new
operator is redefined. A debug version of
new
is included in the
debug heap that records the file and line number of each allocation. This can go a
long way toward detecting the cause of a leak.
The first few lines set the behavior of the debug heap. The first flag tells the debug
heap to keep deallocated blocks around in a special list instead of recycling them
back into the usable memory pool. You might use this flag to help you track a mem-
ory corruption or simply alter your processes
'
memory space in the hopes that a