Simvik

Remove the padding

Reorder struct members to shrink it from 12 bytes to 8. An easy embedded C problem (Structs, unions and memory layout), run and graded in the browser.

easy · Structs, unions and memory layout · padding · alignment

The compiler inserts padding so that every member sits at a multiple of its own alignment. As written, sample_t occupies 12 bytes, of which 4 are padding. A log of 10,000 samples wastes 40 KB.

Reorder the members so that sizeof(sample_t) is 8. Keep all four members with the same names and types, and do not use packing attributes or pragmas.

Starter code

typedef struct {
  uint8_t flags;
  uint32_t timestamp;
  uint8_t channel;
  uint16_t value;
} sample_t;

Example tests

Size is 8 bytes

printf("%u\n", (unsigned)sizeof(sample_t));

Expected output:

8

All members still work

sample_t s = { .flags = 0x81, .timestamp = 123456, .channel = 3, .value = 999 };
printf("%u %u %u %u\n", s.flags, s.timestamp, s.channel, s.value);

Expected output:

129 123456 3 999

Learn it first

More Structs, unions and memory layout problems