0
0
Embedded Cprogramming~5 mins

Struct packing and alignment in Embedded C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is struct alignment in C programming?
Struct alignment means arranging data in memory so that each member starts at an address that matches its size or a specific boundary. This helps the processor access data faster.
Click to reveal answer
beginner
What does struct packing do?
Struct packing removes or reduces the padding between members of a struct, making the struct use less memory but possibly slowing down access.
Click to reveal answer
beginner
Why do compilers add padding inside structs?
Compilers add padding to align data members to their natural boundaries, which makes data access faster on the CPU.
Click to reveal answer
intermediate
How can you tell the compiler to pack a struct in embedded C?
You can use compiler-specific directives like __attribute__((packed)) in GCC or #pragma pack(1) to tell the compiler not to add padding.
Click to reveal answer
intermediate
What is a downside of using packed structs?
Packed structs can cause slower access or even hardware faults on some CPUs because data members may not be aligned properly.
Click to reveal answer
What is the main reason for adding padding inside a struct?
ATo reduce the size of the struct
BTo align data members for faster CPU access
CTo encrypt the data
DTo make the struct harder to read
Which directive is commonly used in GCC to pack a struct?
A__packed__
B#pragma align
C#include <packed.h>
D__attribute__((packed))
What happens if you pack a struct that contains 4-byte integers on a CPU requiring 4-byte alignment?
AAccess might be slower or cause faults
BThe struct size increases
CThe CPU runs faster
DThe struct is automatically aligned
If a struct has members of types char, int, and char, what will the compiler likely do?
AAdd padding after the first char to align the int
BPlace all members back-to-back with no padding
CAdd padding only at the end
DRearrange members automatically
What is the effect of #pragma pack(1) in embedded C?
AIt aligns all members to 4 bytes
BIt doubles the size of the struct
CIt packs the struct with 1-byte alignment, removing padding
DIt disables struct usage
Explain what struct packing and alignment mean and why they matter in embedded C programming.
Think about how data is arranged in memory and how CPUs prefer aligned data.
You got /4 concepts.
    Describe a scenario in embedded systems where you would want to use struct packing and what risks it might bring.
    Consider limited memory devices and hardware communication protocols.
    You got /4 concepts.