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?
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 packwhich 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: