Struct Padding
Problem
I show you a C struct and ask for sizeof on a typical 32-bit target. Then I ask you to write a function that computes it: given the field types in declaration order, return the struct size with natural alignment padding.
Rules I state for the exercise: char is 1 byte / 1-aligned, short 2/2, int and float 4/4, double 8/8, pointers 4/4. Every field starts at an offset that is a multiple of its alignment, and the total size is rounded up to a multiple of the largest alignment in the struct.
Examples
Example 1 — ["char", "int", "char"]
char at 0, then 3 bytes padding, int at 4-7, char at 8, tail padding to 12. Answer: 12.
Example 2 — ["char", "char", "int"]
Same fields, reordered: chars at 0 and 1, padding 2-3, int at 4-7. Answer: 8. This is the point of the question: field order changes memory.
Example 3 — ["double", "char"] → 16. ["char"] → 1.
Constraints
- 1 to 64 fields, only the types listed above.
- No
#pragma pack; ask me if you want to discuss what it would change. - Then explain: why does the compiler pad at all, and what happens on a Cortex-M if you read a misaligned
intthrough a cast pointer.
What they look for
Correct offset arithmetic (offset = roundUp(offset, align)), remembering the tail padding, and being able to say why (bus access alignment, atomicity of aligned loads). Bonus points for mentioning offsetof, _Alignof, and that reordering fields by decreasing size minimises padding.