void.pointer
void.pointer

Reputation: 26405

MSVC initialization of heap when padding is involved

The MSVC memory manager has certain hexidecimal codes it uses in debug builds to mark memory depending on what operation was performed. These are documented here.

In particular, the code 0xCDCDCDCD is used to mark allocated but uninitialized heap memory. Suppose I have the following structure:

struct Test
{
   bool foo;
   int value;

   Test() : foo(false), value(0) {}
};

When I allocate this object, will my memory look like this (note that I am writing out the hexidecimal bytes as they would appear in-order, endianness hasn't been considered for this example)?

00 CD CD CD CD 00 00 00 00

Above, 00 CD CD CD represents the 4-byte aligned boolean. The last 3 bytes are 0xCD because the memory manager initialized those values to CD, however the actual initialization of that boolean in the structure only touches 1 byte since a boolean represents only 1 byte on my machine.

Is this the correct behavior?

Upvotes: 0

Views: 205

Answers (2)

Hans Passant
Hans Passant

Reputation: 942197

There's nothing that would stop the code generator from writing 4 bytes if that produces faster code. Or use memset(), a common optimization in the MSVC compiler. But that obviously didn't happen. Either way is correct, reading the structure padding is undefined behavior.

Upvotes: 1

Mark Tolonen
Mark Tolonen

Reputation: 178045

Just try it. Make sure to compile with /MDd or the like to link to the debug runtime. (The answer is yes in VS2010).

Upvotes: 3

Related Questions