Is zero initialization of structures guaranteed to wipe padded areas?

前端 未结 3 1735
太阳男子
太阳男子 2020-12-19 00:12

Suppose I have the following structure:

typedef struct
{
    unsigned field1 :1;
    unsigned field2 :1;
    unsigned field3 :1;
} mytype;

3条回答
  •  庸人自扰
    2020-12-19 00:39

    Yes and no. The actual standard, C11, specifies:

    If an object that has static or thread storage duration is not initialized explicitly, then:

    • ....

    • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    So this only holds for objects of static storage, at a first view. But then later it says in addition:

    If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

    So this means that padding inside sub-structures that are not initialized explicitly is zero-bit initialized.

    In summarry, some padding in a structure is guaranteed to be zero-bit initialized, some isn't. I don't think that such a confusion is intentional, I will file a defect report for this.

    Older versions didn't have that at all. So with most existing compilers you'd have to be even more careful, since they don't implement C11, yet. But AFAIR, clang already does on that behalf.

    Also be aware that this only holds for initialization. Padding isn't necessarily copied on assignment.

提交回复
热议问题