skip to content

In Rust, why is a struct with fields `flag: u8, id: u32, kind: u8` 8 bytes by default but 12 bytes with `#[repr(C)]`?

level: juniorimportance: should knowfreq 45%

answer

  1. padding follows alignment
  2. the default repr has freedom
  3. declaration order vs chosen order
  4. C keeps the order you wrote

basics

~20 s

The default repr(Rust) lets rustc reorder fields, so it can put the u32 first and both u8 fields after it, padding only to 8. repr(C) keeps declaration order, so padding follows each u8 and the size grows to 12.

solid answer

~40 s

A `u32` must sit at an offset divisible by 4, and a struct's size is always a multiple of its alignment. Under the default `repr(Rust)`, rustc may order fields however it likes; rustc 1.99.1 puts `id` at offset 0 and the two bytes at 4 and 5, then pads to 8. `#[repr(C)]` fixes declaration order: `flag` at 0, three padding bytes, `id` at 4, `kind` at 8, three more padding bytes, 12 in total. The default layout is a compiler choice, not a promise: the Reference guarantees only aligned, non-overlapping fields, and the order can change between compilations. So you write `#[repr(C)]` when the bytes must match something outside the program, such as a C header or a wire format, and leave the default everywhere else.

code

rust · 34 lines
rust
use std::mem::offset_of;

struct Declared {
    flag: u8,
    id: u32,
    kind: u8,
}

#[repr(C)]
struct CLayout {
    flag: u8,
    id: u32,
    kind: u8,
}

fn main() {
    println!("repr(Rust): size {} align {}", size_of::<Declared>(), align_of::<Declared>());
    println!(
        "  offsets flag={} id={} kind={}",
        offset_of!(Declared, flag),
        offset_of!(Declared, id),
        offset_of!(Declared, kind)
    );
    println!("repr(C):    size {} align {}", size_of::<CLayout>(), align_of::<CLayout>());
    println!(
        "  offsets flag={} id={} kind={}",
        offset_of!(CLayout, flag),
        offset_of!(CLayout, id),
        offset_of!(CLayout, kind)
    );
    let d = Declared { flag: 1, id: 2, kind: 3 };
    let c = CLayout { flag: 1, id: 2, kind: 3 };
    let _ = (d.flag, d.id, d.kind, c.flag, c.id, c.kind);
}

go deeper

for a junior

Recall that alignment forces padding, that the default layout may reorder fields, and that #[repr(C)] keeps declaration order. Be able to work out 12 and 8 for this struct.

for a middle

Walk through the repr(C) algorithm field by field, and say which guarantees repr(Rust) actually makes: aligned, non-overlapping fields and nothing about order.

for a senior

Explain where layout becomes a contract: a C header, a wire format, a pointer cast. Show offset_of! to check offsets, and point out that byte order is a separate problem.

for a principal

Argue for leaving the default layout alone on internal types so rustc can shrink them, and reserving repr(C) for the few types that cross a boundary.

## Size, alignment and padding Every Rust type has two layout numbers you can read with `std::mem::size_of` and `std::mem::align_of` (both are in the prelude, so plain `size_of::<T>()` works): - **Alignment** is the power of two that every address holding the value must be a multiple of. A `u8` has alignment 1; a `u32` has alignment 4 on mainstream targets. - **Size** is the distance between consecutive elements of an array of the type, padding included. The Reference states that a size is **always a multiple of the alignment**. - **Padding** is the unused bytes a struct needs so each field lands on an offset its alignment allows, plus the tail bytes that round the size up to a multiple of the struct's alignment. The struct in the question has 6 bytes of real data (`1 + 4 + 1`) and alignment 4, so its smallest possible size is 8. Whether it reaches 8 depends on the order of the fields in memory. ## What the default `repr(Rust)` promises A struct with no `repr` attribute uses the **Rust representation**. The Reference lists its only guarantees, the ones soundness needs: 1. The offset of each field is divisible by that field's alignment. 2. The alignment of the struct is at least the largest alignment of its fields. 3. The fields do not overlap, although the order in memory "does not have to be the same as the order in which the fields are specified". 4. A struct with no fields, or only zero-sized fields, is itself zero-sized. Nothing else is promised. The Reference also warns that layout "can be changed with each compilation". In practice rustc reorders fields to shrink padding, but you cannot rely on any particular order, and the exact order you observe today is an implementation detail. ## What `#[repr(C)]` adds `#[repr(C)]` replaces the compiler's freedom with a fixed algorithm, the one C compilers use: 1. Start at offset 0. 2. For each field **in declaration order**, add padding until the offset is a multiple of the field's alignment, place the field, and advance by its size. 3. Round the final offset up to a multiple of the struct's alignment, which is the largest field alignment. For `flag: u8, id: u32, kind: u8` that gives `flag` at 0, padding 1 to 3, `id` at 4, `kind` at 8, tail padding 9 to 11: **12 bytes**. Writing the fields as `id, flag, kind` would bring a `repr(C)` struct back to 8, which is why C programmers order fields by hand. | | `repr(Rust)` (default) | `#[repr(C)]` | |---|---|---| | Field order in memory | compiler's choice | declaration order | | Padding | usually minimised | whatever declaration order forces | | Guaranteed across compilations | no | yes | | Matches a C struct with the same fields | not promised | yes, by design | | Size of this example on rustc 1.99.1 | 8 | 12 | ## Measuring it `std::mem::offset_of!` reports where a field actually landed, so you can see the reordering instead of guessing. The program below prints the sizes and offsets for both versions; the `repr(Rust)` offsets it prints describe this compiler build, not a guarantee. ## When the declared order matters You reach for `#[repr(C)]` when bytes leave the type system: - **Interoperating with C**: a struct passed by pointer to a C library must match the C declaration field for field. - **Wire and file formats**: a packet header or file record whose fields sit at fixed offsets. - **Reinterpreting memory**: casting a pointer from one type to another is only meaningful when both layouts are defined. `repr(C)` fixes order and padding, not byte order: a big-endian wire field still needs `u32::from_be_bytes` or `to_be`. And it does not remove padding; removing padding is the job of the `packed` modifier. ## Raising alignment with `repr(align(N))` `align` and `packed` are modifiers on top of a representation. `#[repr(align(64))]` raises a type's alignment to 64, so its size rounds up to 64 as well; a lower value than the type already needs is ignored. A common use is giving each per-thread counter its own cache line. On its own, `align` makes no promise about field order; combine it as `#[repr(C, align(64))]` when you need both.

  • If you reorder the fields of the `#[repr(C)]` struct to `id: u32, flag: u8, kind: u8`, what size do you get, and why?
    8 bytes. `id` sits at 0, `flag` at 4 and `kind` at 5, which are allowed because a `u8` needs no alignment, and the size rounds up from 6 to 8 because the struct's alignment is 4. `repr(C)` never reorders, so ordering fields from largest to smallest alignment is how you minimise padding by hand.
  • Does adding `#[repr(align(16))]` to the default-layout struct change its size, and does it fix the field order?
    It raises the alignment to 16, so the size rounds up to 16. It does not fix the order: `align` is a modifier, and on the Rust representation the fields may still be reordered. Write `#[repr(C, align(16))]` when you need declaration order and the higher alignment together.

  • A struct's size is just the sum of its field sizes
  • Rust always stores fields in the order you declare them
  • The offsets rustc picks today are part of the language guarantee
  • repr(C) removes padding between fields
  • repr(C) also converts fields to network byte order