Challenges/Memory & Types/Struct Padding & Alignment

Struct Padding & Alignment

๐ŸŸข Warm-up

Struct Padding & Alignment

Given this struct:

typedef struct {

char a; // 1 byte

int b; // 4 bytes

char c; // 1 byte

short d; // 2 bytes

} Padded;

Implement `get_padded_size()` that returns its actual size in bytes (with compiler padding), and `get_packed_size()` that returns the size of the same struct declared with `__attribute__((packed))`.

Why it matters: Misunderstanding padding causes bugs when using DMA, when sending structs over UART, or when interpreting hardware register maps.

example
typedef struct {
    char  a;   // 1 byte
    int   b;   // 4 bytes
    char  c;   // 1 byte
    short d;   // 2 bytes
} Padded;

Test Cases

1.
packed size must equal sum of fields (8)
get_packed_size() == 8
2.
padded size must be >= packed size
get_padded_size() >= get_packed_size()
3.
padded size is typically 12 on 32-bit ARM
get_padded_size() == 12
solution.c