Article revision Version 1 of 1 Current

Calculate C Struct Padding and Alignment in a Tiny Compiler

Originally published by @nibblebits Nov 11, 2026 at 14:35
View current article
Initial version

Original article publication

This is the article as it appeared before any published revisions.

Snapshot

Article at version 1

Compilers & Toolchains

The members of a C struct can occupy seven bytes while the struct itself occupies twelve. To generate code for a member access such as sample.sequence, a compiler needs the member's byte offset. To index an array of those structs, it also needs the full size of each element.

This example implements both calculations in C11 and compares them with GCC's own layout.

Start with the target's rules

C preserves the declared order of ordinary struct members and allows padding between members and after the last member. The target implementation determines the alignment. For this example, use the default Windows x64 layout for ordinary member types. Each member starts at the next offset that satisfies its alignment. The struct uses the greatest member alignment, and its total size is rounded up to a multiple of that alignment. WG14 C11 draft, §6.7.2.1 · Microsoft x64 aggregate layout

The calculator takes a list of sizes and alignments for already resolved member types. Each alignment is a nonzero power of two, and each member's size is a multiple of its alignment. The caller supplies one offset slot per member and a separate result object. Packed structs, explicitly aligned members, bit-fields, and flexible array members require additional layout rules.

Calculate the padding

Consider the following layout for struct Sample.

Member Size Alignment Offset Bytes used
kind 1 1 0 0
sequence 4 4 4 4–7
flags 2 2 8 8–9

After kind, the next free byte is 1. Rounding that offset up to a multiple of 4 leaves bytes 1–3 as internal padding. The last member ends at offset 10, so two more bytes of padding bring the struct size to 12.

That final rounding matters for arrays. If the stride were 10, the second element would start two bytes past a four-byte boundary. With a stride of 12, each element starts on a suitable boundary and its sequence member stays aligned. Microsoft x64 aggregate layout

Implement the layout pass

For each member, round the current end offset up to the member's alignment, record that offset, and advance by the member's size. After placing all members, round up once more using the greatest alignment.

The rounding helper calculates the padding from the remainder and checks the addition against SIZE_MAX. The placement step separately checks whether the member fits after that padding. These checks let the calculator reject impossible metadata without unsigned arithmetic wrapping to a smaller offset.

Save this as struct_layout.c.

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

struct Field {
    size_t size;
    size_t alignment;
};

struct Layout {
    size_t size;
    size_t alignment;
};

static bool round_up(size_t value, size_t alignment, size_t *result)
{
    const size_t remainder = value % alignment;
    const size_t padding = remainder == 0 ? 0 : alignment - remainder;
    if (value > SIZE_MAX - padding) {
        return false;
    }
    *result = value + padding;
    return true;
}

/* The caller reads offsets and layout only on success. */
static bool layout_struct(const struct Field *fields, size_t count,
                          size_t *offsets, struct Layout *layout)
{
    if (count == 0) {
        return false;
    }

    size_t end = 0;
    size_t max_alignment = 1;

    for (size_t i = 0; i < count; ++i) {
        const size_t size = fields[i].size;
        const size_t alignment = fields[i].alignment;
        if (size == 0 || alignment == 0 ||
            (alignment & (alignment - 1)) != 0 ||
            size % alignment != 0) {
            return false;
        }

        size_t offset;
        if (!round_up(end, alignment, &offset) || size > SIZE_MAX - offset) {
            return false;
        }
        offsets[i] = offset;
        end = offset + size;
        if (alignment > max_alignment) {
            max_alignment = alignment;
        }
    }

    size_t total;
    if (!round_up(end, max_alignment, &total)) {
        return false;
    }
    *layout = (struct Layout){.size = total, .alignment = max_alignment};
    return true;
}

struct Sample {
    uint8_t kind;
    uint32_t sequence;
    uint16_t flags;
};

int main(void)
{
    const struct Field fields[] = {
        {sizeof(uint8_t),  _Alignof(uint8_t)},
        {sizeof(uint32_t), _Alignof(uint32_t)},
        {sizeof(uint16_t), _Alignof(uint16_t)}
    };
    size_t offsets[3];
    struct Layout result;
    if (!layout_struct(fields, 3, offsets, &result)) {
        return 1;
    }

    printf("calculated: offsets %zu, %zu, %zu | size %zu | alignment %zu\n",
           offsets[0], offsets[1], offsets[2], result.size, result.alignment);
    printf("compiler:   offsets %zu, %zu, %zu | size %zu | alignment %zu\n",
           offsetof(struct Sample, kind), offsetof(struct Sample, sequence),
           offsetof(struct Sample, flags), sizeof(struct Sample),
           _Alignof(struct Sample));

    return offsets[0] == offsetof(struct Sample, kind) &&
           offsets[1] == offsetof(struct Sample, sequence) &&
           offsets[2] == offsetof(struct Sample, flags) &&
           result.size == sizeof(struct Sample) &&
           result.alignment == _Alignof(struct Sample) ? 0 : 1;
}

Compare the result with GCC

The demo uses sizeof and _Alignof to obtain the member types' sizes and alignments. It then compares the calculated offsets with offsetof and the calculated aggregate properties with sizeof and _Alignof on struct Sample. A cross-compiler would get the member metadata from its target type information instead of using the host's type sizes. WG14 C11 draft, §§6.5.3.4 and 7.19

In PowerShell with MinGW-w64 GCC targeting x86_64-w64-mingw32, build and run the example.

gcc -std=c11 -O2 -Wall -Wextra -Wconversion -Werror -pedantic struct_layout.c -o struct_layout.exe
.\struct_layout.exe

Both lines agree on the tested target.

calculated: offsets 0, 4, 8 | size 12 | alignment 4
compiler:   offsets 0, 4, 8 | size 12 | alignment 4

Try changing the declaration order and passing the same order to the calculator.

struct CompactSample {
    uint32_t sequence;
    uint16_t flags;
    uint8_t kind;
};

Those fields land at offsets 0, 4, and 6. They end at offset 7, so one byte of trailing padding gives a size of 8 on this target. The offsets changed along with the size. If other code already relies on the original layout, changing the field order changes that interface.

The sample and four additional layouts matched the compiler, including a nested struct, an array member, and a member with eight-byte alignment. Eight rejection cases covered malformed size and alignment inputs and overflow during alignment, member placement, and final rounding.

My compiler course covers structures, datatype sizes, alignment, and member offsets as part of building a compiler. Creating a C Compiler From Scratch Video Course!

compilerscabistruct-layoutalignment