简体   繁体   中英

Does .NET initialize struct padding to zero?

When .NET initializes a struct to zero, does it zero out the padding as well?

I ask because I'm wondering about the limitations of doing bitwise comparisons on unmanaged structs.

Note how CanCompareBits not only checks that the type is unmanaged ( !mt->ContainsPointers() ), but also that it is tightly packed ( !mt=>IsNotTightlyPacked ). Mind the double negative on the latter: it requires that the type is tightly packed.

// Return true if the valuetype does not contain pointer and is tightly packed
FCIMPL1(FC_BOOL_RET, ValueTypeHelper::CanCompareBits, Object* obj)
{
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    _ASSERTE(obj != NULL);
    MethodTable* mt = obj->GetMethodTable();
    FC_RETURN_BOOL(!mt->ContainsPointers() && !mt->IsNotTightlyPacked());
}
FCIMPLEND

This code seems to imply that structs with padding are unsuitable for bitwise comparisons. When is this true, and why?

My assumption is that this has to do with padding initialization, but perhaps there is more going on.

Struct padding is explicitly documented as being indeterminant.

From https://learn.microsoft.com/en-us/do.net/csharp/language-reference/language-specification/unsafe-code :

For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of the struct. The contents of the bits used as padding are indeterminate.

This matches the documentation for C/C++ structs, which I think is no coincidence. The ISO C99 standard states:

When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values."

So to answer your questions:

"When .NET initializes a struct to zero, does it zero out the padding as well?" - Undefined, so you cannot rely on it.

"When is this true?" - Always.

"Why" - If that means "why is the padding not initialised", I can only surmise: Probably for performance reasons, and for compatibility with C/C++ for Interop calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM