Game Development Reference
In-Depth Information
protected:
int *leaked;
LeakyMemory() { leaked = new int[128]; }
~LeakyMemory() { delete [] leaked; }
};
This code might look fine, but there ' s a potential memory leak in there. If this class is
instantiated and is referenced by a pointer to SomeBaseClass , the destructor will
never get called.
void main()
{
LeakyMemory *ok = new LeakyMemory;
SomeBaseClass *bad = new LeakyMemory;
delete ok;
delete bad;
// MEMORY LEAK RIGHT HERE!
}
You fix this problem by declaring the destructor in LeakyMemory as virtual. Mem-
ory leaks are easy to fix if the leaky code is staring you in the face. This isn
t always
the case. A few bytes leaked here and there as game objects are created and destroyed
can go unnoticed for a long time until it is obvious that your game is chewing up
memory without any valid reason.
Memory bugs and leaks are amazingly easy to fix, but tricky to find, if you use a
memory allocator that doesn
'
t have special code to give you a hand. Under Windows,
the C runtime library lends a hand under the debug builds with the debug heap. The
debug heap sets the value of uninitialized memory and freed memory.
'
n Uninitialized memory allocated on the heap is set to 0xCDCDCDCD.
n Uninitialized memory allocated on the stack is set to 0xCCCCCCCC. This is
dependent on the /GX compiler option in Microsoft Visual Studio.
n Freed heap memory is set to 0xFEEEFEEE, before it has been reallocated.
Sometimes, this freed memory is set to 0xDDDDDDDD, depending on how the
memory was freed.
n The lead byte and trailing byte to any memory allocated on the heap is set to
0xFDFDFDFD.
Windows programmers should commit these values to memory. They
'
ll come in
handy when you are viewing memory windows in the debugger.
Search WWH ::




Custom Search