Which of the following are true in Standard C?
(A) The sizeof a structure is equal to:
the relative address of its last member plus the
sizeofits last member. (I know this cannot be true.)the relative address of its last member plus the alignment value (as obtained by the
_Alignofoperator) of its last member. (This cannot be true also, because there are cases where thesizeofa type may be larger than its_Alignofvalue. Seelong doublein 32 bit Windows GCC:sizeofis 12,_Alignofis 4.)the relative address of its last member plus the alignment value of the structure itself. (This cannot be true also, as explained in the previous statement.)
the relative address of its last member plus the maximum of the last member's size and the alignment value of the structure itself.
something else.
By relative address I mean the distance between the starting byte of its last member and the starting byte of its first member (or the structure itself) which can be obtained with the offsetof macro like this: offsetof(struct st, last_member).
(B) The _Alignof value of a structure is equal to:
the
_Alignofvalue of its member with the largest_Alignofvalue.something else.
Notes:
I am not talking about specific implementations on specific environments, but rather how a "Stardard C (C18)"-compliant implementation should behave theoretically.
_Alignofis the standard C operator andalignofis its macro synonym defined instdalign.hheader.
The answer for A is “something else.”
The size of a structure must be at least the offset of its last member plus the size of that member plus enough padding bytes to make the structure’s size a multiple of its alignment requirement (which equals the largest alignment requirement of any of its members). A C implementation may add additional padding bytes in multiples of the alignment requirement, although I know of none that do.
The answer for B is the alignment requirement of the structure (its
_Alignofvalue) equals strictest alignment requirement of its members (the largest_Alignofvalue of them).In particular, note that C 2018 6.2.7 4 says “… Every valid alignment value shall be a nonnegative integral power of two.” Thus, if any alignment satisfies the strictest member alignment requirement, it satisfies each member alignment requirement, so it is sufficient.