I know that the compiler will sometimes initialize memory with certain patterns such as 0xCD and 0xDD. What I want to know is when and why this happens.
When
Is this specific to the compiler used?
Do malloc/new and free/delete work in the same way with regard to this?
Is it platform specific?
Will it occur on other operating systems, such as Linux or VxWorks?
Why
My understanding is this only occurs in Win32 debug configuration, and it is used to detect memory overruns and to help the compiler catch exceptions.
Can you give any practical examples as to how this initialization is useful?
I remember reading something (maybe in Code Complete 2) saying that it is good to initialize memory to a known pattern when allocating it, and certain patterns will trigger interrupts in Win32 which will result in exceptions showing in the debugger.
How portable is this?
A quick summary of what Microsoft’s compilers use for various bits of unowned/uninitialized memory when compiled for debug mode (support may vary by compiler version):
Disclaimer: the table is from some notes I have lying around – they may not be 100% correct (or coherent).
Many of these values are defined in vc/crt/src/dbgheap.c:
There are also a few times where the debug runtime will fill buffers (or parts of buffers) with a known value, for example, the ‘slack’ space in
std::string‘s allocation or the buffer passed tofread(). Those cases use a value given the name_SECURECRT_FILL_BUFFER_PATTERN(defined incrtdefs.h). I’m not sure exactly when it was introduced, but it was in the debug runtime by at least VS 2005 (VC++8).Initially, the value used to fill these buffers was
0xFD– the same value used for no man’s land. However, in VS 2008 (VC++9) the value was changed to0xFE. I assume that’s because there could be situations where the fill operation would run past the end of the buffer, for example, if the caller passed in a buffer size that was too large tofread(). In that case, the value0xFDmight not trigger detecting this overrun since if the buffer size were too large by just one, the fill value would be the same as the no man’s land value used to initialize that canary. No change in no man’s land means the overrun wouldn’t be noticed.So the fill value was changed in VS 2008 so that such a case would change the no man’s land canary, resulting in the detection of the problem by the runtime.
As others have noted, one of the key properties of these values is that if a pointer variable with one of these values is de-referenced, it will result in an access violation, since on a standard 32-bit Windows configuration, user mode addresses will not go higher than 0x7fffffff.