cstructmemory-layout

Struct memory layout in C


I have a C# background. I am very much a newbie to a low-level language like C.

In C#, struct's memory is laid out by the compiler by default. The compiler can re-order data fields or pad additional bits between fields implicitly. So, I had to specify some special attribute to override this behavior for exact layout.

AFAIK, C does not reorder or align memory layout of a struct by default. However, I heard there's a little exception that is very hard to find.

What is C's memory layout behavior? What should be re-ordered/aligned and not?


Solution

  • In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

    Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

    Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

    From C99 §6.7.2.1:

    12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

    13 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.