Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any guarantees about C struct packing?

Tags:

c

packing

Are there any guarantees regarding packing of structs in C?

Just as an example, provided that sizeof(double) == 8, is it guaranteed that sizeof(struct { double x, y; }) == 16?

I am aware that the intention behind this question conflicts with strict aliasing rules, therefore assume strict aliasing is disabled, e.g. in the case of gcc with -fno-strict-aliasing.

To avoid any further speculations: The intention is knowing about compatibility of a struct with its explicitly packed counterpart. Note that aliasing is relevant even in the following case: Are C-structs with the same members types guaranteed to have the same layout in memory? . No need to worry about me wanting to access single bytes.

like image 437
Pedro Avatar asked Dec 05 '17 21:12

Pedro


1 Answers

The only thing the C standard says regarding struct packing is that no padding may exist at the start of a struct. It makes no guarantees regarding padding between fields or at the end.

Section 6.7.2.1 of the C standard says the following regarding structures:

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

...

17 There may be unnamed padding at the end of a structure or union.

That being said, most implementations tend to be fairly consistent with how structures are packed. Non-struct variables n bytes in size (or arrays such variables) will tend to start on an n byte boundary. A struct within a struct will tend to be aligned based on the alignment of its subfields.

The Lost Art of C Structure Packing goes into this in much more detail.

like image 70
dbush Avatar answered Oct 14 '22 15:10

dbush