Why does the not allocated memory is marked like 0

2020-07-09 08:04发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?

Why is memory I haven't initialized set to 0xCC?

Setting the memory to 0xCC will decrease performance, so there must be a reason for filling the memory with this byte.

回答1:

Inside CRT: Debug Heap Management

When you compile a debug build of your program with Visual Studio and run it in debugger, you can see that the memory allocated or deallocated has funny values, such as...

0xCC When the code is compiled with the /GZ option, uninitialized variables are automatically assigned to this value (at byte level).

Magic Number on Wiki:

CCCCCCCC Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory

In Visual Studio CRT Source, \VC\crt\src\malloc.h:

#define _ALLOCA_S_STACK_MARKER  0xCCCC

// ...

#undef _malloca
#define _malloca(size) \
__pragma(warning(suppress: 6255)) \
    ((((size) + _ALLOCA_S_MARKER_SIZE) <= _ALLOCA_S_THRESHOLD) ? \
        _MarkAllocaS(_alloca((size) + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_STACK_MARKER) : \
        _MarkAllocaS(malloc((size) + _ALLOCA_S_MARKER_SIZE), _ALLOCA_S_HEAP_MARKER))


回答2:

The compiler does this for you in debug mode, so that if you accidentally read uninitialized memory, you'll see the distinctive 0xCC value, and recognize that you (probably) read uninitialized memory. The 0xCC value has a lot of other useful properties, for example it is the machine language instruction for invoking a software breakpoint should you accidentally execute some uninitialized memory.

The basic principle: make it easy to identify values that come from reading uninitialized memory.

This doesn't happen in your release builds.

This technique was introduced in Writing Solid Code.



回答3:

When the code is compiled with the /GZ option, uninitialized variables are automatically assigned to this value (at byte level).

0xCC is machine code instruction to invoke break point. For more information see another question.