Reputation: 9203
Say I have a struct with 2 fields and the implementation of C that I have also has some padding between these fields.
If I create two variables of the struct and assign one to another, will the padding be guaranteed to be equal?
I know that for most compilers it would be so (because they just call memcpy), but I want to know what is specified about the padding in the standard?
Intention for this question is, can I use memcmp
to check equality of structs.
Say I have a compiler which emits code that just assigns all the members of the struct instead of doing memcpy
, will it be a valid implementation of the assignment of struct operation?
Upvotes: 6
Views: 673
Reputation: 123468
6.2.6.1 General
...
6 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.51) The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.
7 When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.
51) Thus, for example, structure assignment need not copy any padding bits.
Footnote 51 directly addresses your question - contents of padding bits may not be copied over in assignment, so memcmp
may not work for comparing two structs
for equality.
Upvotes: 6
Reputation: 18341
The standard says in a note 51 of 6.2.6.1 General:
Thus, for example, structure assignment need not copy any padding bits.
Upvotes: 7
Reputation: 35154
I don't think that you can use memcmp
, because the memory between the members (i.e. the content in the "padding"-area) is not guaranteed to have a certain value, and assigning such a struct-object to another is not required to copy the padding content as well.
Upvotes: 1