"is it guaranteed that the padding bits of “zeroed” structure will be zeroed in c?" Code Answer

1

the short answer to your first question is "no".

while an appropriate call of memset(), such as memset(&some_struct_instance, 0, sizeof(some_struct)) will set all bytes in the structure to zero, that change is not required to be persistent after "some use" of some_struct_instance, such as setting any of the members within it.

so, for example, there is no guarantee that some_struct_instance.some_enum = three (i.e. storing a value into a member) will leave any padding bits in some_struct_instance unchanged. the only requirement in the standard is that values of other members of the structure are unaffected. however, the compiler may (in emitted object code or machine instructions) implement the assignment using some set of bitwise operations, and be allowed to take shortcuts in a way that doesn't leave the padding bits alone (e.g. by not emitting instructions that would otherwise ensure the padding bits are unaffected).

even worse, a simple assignment like some_struct_instance = some_other_struct_instance (which, by definition, is the storing of a value into some_struct_instance) comes with no guarantees about the values of padding bits. it is not guaranteed that the padding bits in some_struct_instance will be set to the same bitwise values as padding bits in some_other_struct_instance, nor is there a guarantee that the padding bits in some_struct_instance will be unchanged. this is because the compiler is allowed to implement the assignment in whatever means it deems most "efficient" (e.g. copying memory verbatim, some set of member-wise assignments, or whatever) but - since the value of padding bits after the assignment are unspecified - is not required to ensure the padding bits are unchanged.

if you get lucky, and fiddling with the padding bits works for your purpose, it will not be because of any support in the c standard. it will be because of good graces of the compiler vendor (e.g. choosing to emit a set of machine instructions that ensure padding bits are not changed). and, practically, there is no guarantee that the compiler vendor will keep doing things the same way - for example, your code that relies on such a thing may break when the compiler is updated, when you choose different optimisation settings, or whatever.

since the answer to your first question is "no", there is no need to answer your second question. however, philosophically, if you are trying to store data in padding bits of a structure, it is reasonable to assert that someone else - crazy or not - may potentially attempt to do the same thing, but using an approach that messes up the data you are attempting to pass around.

By Natalja Olefire on October 11 2022

Answers related to “is it guaranteed that the padding bits of “zeroed” structure will be zeroed in c?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.