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?
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required.
Yes if the structure is of the same type. Think it as a memory copy. Keep in mind that there's no deep copy, pointed to memory isn't copied.
Generally packed structures are used: To save space. To format a data structure to transmit over network without depending on each architecture alignment of each node of the network.
The standard says in a note 51 of 6.2.6.1 General:
Thus, for example, structure assignment need not copy any padding bits.
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.
C 2011 Online Draft
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With