Simvik

Predict sizeof

Compute the size of a struct from the sizes of its members. A hard embedded C problem (Structs, unions and memory layout), run and graded in the browser.

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

Implement the compiler's layout rule. sizes lists the size in bytes of each member of a struct, in declaration order. Every size is 1, 2, 4 or 8, and a member's alignment equals its size.

Return what sizeof the struct would be: each member is placed at the next offset that is a multiple of its alignment, and the total is rounded up to a multiple of the largest alignment. An empty list gives 0.

Starter code

size_t padded_size(const uint8_t *sizes, size_t n) {
  // {1, 4, 1, 2} -> 12, {4, 2, 1, 1} -> 8
  return 0;
}

Example tests

Badly ordered members

const uint8_t m[] = { 1, 4, 1, 2 };
printf("%u\n", (unsigned)padded_size(m, 4));

Expected output:

12

Well ordered members

const uint8_t m[] = { 4, 2, 1, 1 };
printf("%u\n", (unsigned)padded_size(m, 4));

Expected output:

8

Learn it first

More Structs, unions and memory layout problems