pointers-memory · intermediate · ~15 min

Manual struct padding & field offset math

Master struct alignment, member padding, and trailing structure padding calculations.

Challenge

To maximize memory bus throughput, C compilers automatically insert padding bytes between struct members so that each field is aligned to a multiple of its natural alignment requirement.

Your Task

Implement:

size_t compute_struct_size(const size_t *field_sizes, const size_t *field_aligns, size_t num_fields, size_t *offsets);

Compute the field offsets and total struct size according to standard C ABI struct alignment rules.

Rules

  1. If field_sizes == NULL, field_aligns == NULL, or num_fields == 0, return 0.
  2. Start with current_offset = 0 and max_align = 1.
  3. For each field i from 0 to num_fields - 1:
    • Round current_offset up to the next multiple of field_aligns[i]: (current_offset + align - 1) & ~(align - 1).
    • If offsets != NULL, record offsets[i] = current_offset.
    • Advance current_offset += field_sizes[i].
    • Track the maximum field alignment: max_align = max(max_align, field_aligns[i]).
  4. Round the final current_offset up to the nearest multiple of max_align (struct trailing padding).
  5. Return the total struct size.

Input format

field_sizes: array of byte sizes; field_aligns: array of alignments; num_fields: count; offsets: output array.

Output format

Returns total aligned struct size in bytes.

Constraints

C11 freestanding struct layout arithmetic.

Starter code

#include <stddef.h>

/* Compute member offsets and total struct size with internal and trailing padding.
   Store offsets in offsets array (if non-NULL) and return total struct size. */
size_t compute_struct_size(const size_t *field_sizes, const size_t *field_aligns, size_t num_fields, size_t *offsets) {
    (void)field_sizes; (void)field_aligns; (void)num_fields; (void)offsets;
    return 0;
}

Common mistakes

Forgetting trailing padding aligned to max_align; calculating alignment without bitwise masking.

Edge cases to handle

Single field struct; already aligned fields; struct needing trailing padding for array stride.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.