skip to content

A Rust `#[repr(C, packed)]` packet header fails with E0793 at `&h.seq` and at `println!("{}", h.len)`: why, and how do you read those fields?

level: seniorimportance: should knowfreq 25%

answer

  1. packed drops alignment to 1
  2. a reference promises alignment
  3. println! borrows its arguments
  4. copy out or read_unaligned

basics

~20 s

repr(packed) lowers the struct's alignment to 1, so a u32 or u16 field may be misaligned, and even creating a misaligned reference is undefined behaviour. Copy the field out ({ h.len }) or take &raw const and call read_unaligned.

solid answer

~50 s

`#[repr(C, packed)]` removes all padding and gives the struct alignment 1, so `seq: u32` after a `u8` lands at offset 1, and the whole header may sit at any address. A `&u32` promises 4-byte alignment, and the Reference counts even creating a misaligned reference as undefined behaviour, so rustc rejects it with E0793, inside `unsafe` too. `println!` takes a reference to each argument, which is why `h.len` fails as well, and it fails even for fields at even offsets, because the struct's own address is unknown. The fixes: read by value (`let seq = h.seq;`), wrap a format argument in braces (`{ h.len }`), or take a raw pointer with `&raw const h.seq` (Rust 1.82) and call `read_unaligned`. Keep `C` in the attribute: since Rust 1.80 rustc may reorder the fields of a type that is only `packed`.

code

rust · 13 lines
rust
#[repr(C, packed)]
struct WireHeader {
    version: u8,
    seq: u32,
    len: u16,
}

fn main() {
    let h = WireHeader { version: 1, seq: 0xDEAD_BEEF, len: 512 };
    let v: &u8 = &h.version; // fine: u8 needs no alignment
    let s: &u32 = &h.seq; // rejected
    println!("{v} {s} {}", h.len);
}

go deeper

for a junior

Recall that packed removes padding and that rustc refuses references to packed fields with E0793.

for a middle

Explain why println! triggers the same error, and know the three fixes: copy out, braces, and read_unaligned through &raw const.

for a senior

Show why even an unused misaligned reference is undefined behaviour, why *p on the raw pointer is still wrong, and why the attribute must say C as well as packed.

for a principal

Weigh a packed struct against parsing fields with from_be_bytes: packed fixes offsets but not byte order, validity or the cost of unaligned access.

## The scenario A wire format defines a 7-byte header: a 1-byte version, a 4-byte sequence number and a 2-byte length, with no gaps. The natural Rust declaration is: ```rust #[repr(C, packed)] struct WireHeader { version: u8, seq: u32, len: u16, } ``` `size_of::<WireHeader>()` is 7 and `align_of::<WireHeader>()` is 1, which matches the wire. The trouble starts when code borrows a field. ## What `packed` does `packed` is a **modifier** that lowers alignment. `#[repr(packed)]` is the same as `#[repr(packed(1))]`. The Reference sets out its rules: - each field is positioned using the smaller of the packed value and the field's own alignment, so with `packed(1)` every field is treated as 1-aligned; - inter-field padding is the minimum those alignments need, so `packed(1)` leaves **no padding at all**; - the struct's own alignment drops to the packed value, here 1; - on its own, `packed` gives **no guarantee about field order**. So `seq` sits at offset 1 and `len` at offset 5. Because the struct is 1-aligned, the header itself may also sit at any address, for example at an odd offset into a receive buffer. ## Why a reference to the field is an error A Rust reference `&T` must always be aligned for `T`. The Reference's list of undefined behaviour includes producing a misaligned reference, and rustc's own note for this error says "creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)". The compiler therefore refuses `&h.seq` with **E0793**, "reference to field of packed struct is unaligned". An `unsafe` block does not change this: the error-code page says so directly. Two details catch people: 1. **Formatting borrows.** `println!("{}", h.len)` takes `&h.len` internally, so it fails with the same E0793 although no `&` appears in your code. 2. **The offset is not the point.** In a packed struct starting with two `u16` fields, a `u16` at offset 4 still fails: rustc's note says "this struct is 1-byte aligned, but the type of this field may require higher alignment". Only fields whose type has alignment 1, such as `u8`, can be borrowed. ## The three ways to read a packed field | Need | Write | Why it works | |---|---|---| | The value | `let seq = h.seq;` | a by-value read is compiled as an unaligned load; no reference exists | | A formatting argument | `println!("{}", { h.len });` | the braces make a temporary copy, and the macro borrows the copy | | A pointer | `let p = &raw const h.seq;` then `unsafe { p.read_unaligned() }` | a raw pointer may be misaligned; `read_unaligned` does not assume alignment | Writing works the same way: assign `h.len = 8;` directly, or use `&raw mut h.len` and `write_unaligned`. Dereferencing the raw pointer with `*p` would be undefined behaviour again, because a plain load through a raw pointer must still be aligned; rustc's help text for E0793 says exactly that. The `&raw const` and `&raw mut` operators were stabilised in Rust 1.82; older code writes `std::ptr::addr_of!(h.seq)` for the same pointer. ## Why the attribute says `C, packed` The nomicon advises being explicit with `repr(C, packed)`, and since Rust 1.80 rustc is allowed to reorder the fields of a type marked `repr(packed(1))` without `C`. rustc 1.99.1 still keeps declaration order in a quick test, but a wire format cannot depend on an unpromised choice. `C` fixes the order; `packed` removes the gaps. ## What `packed` still does not do - **Byte order.** The wire's big-endian `seq` is still a native-endian `u32` in memory. Convert with `u32::from_be(h.seq)` or parse the bytes with `u32::from_be_bytes`. - **Speed for free.** Unaligned loads may be slower or need extra instructions on some targets; the nomicon calls `packed` "not to be used lightly". - **Validating bytes.** Turning a received `&[u8]` into a `&WireHeader` raises separate questions about valid values and aliasing, which belong to the material on undefined behaviour; many parsers avoid it by reading each field with `from_be_bytes` from the slice. A derived `Debug` or `PartialEq` on a packed struct works when the fields are `Copy`, because the derive copies each field out instead of borrowing it.

  • Why is `unsafe { *(&raw const h.seq) }` still wrong even though it avoids creating a reference?
    A plain dereference of a raw pointer performs an ordinary load, and an ordinary load must be aligned for its type; only the reference requirement goes away. For a possibly misaligned `*const u32`, call `read_unaligned`, which copies the bytes without assuming alignment. rustc's E0793 help text spells out this exact trap.
  • When would `#[repr(C, packed(2))]` be enough instead of `packed`?
    When the format aligns fields to 2 bytes but not more. `packed(2)` caps each field's alignment at 2, so a `u32` may follow a `u16` with no gap, while a `u8` followed by a `u16` still gets one byte of padding. References to `u16` fields are then aligned and allowed, while references to `u32` fields are still rejected with E0793.

  • Wrapping &h.seq in an unsafe block makes it acceptable
  • A misaligned reference is fine as long as you never read through it
  • Fields at even offsets of a packed struct can always be borrowed
  • repr(packed) alone keeps fields in declaration order
  • Dereferencing a raw pointer to a packed field is always safe
  • repr(C, packed) also stores multi-byte fields in network byte order

Assumes Rust 1.99 on edition 2024; &raw const and &raw mut arrived in 1.82, and 1.80 allowed rustc to reorder fields of a repr(packed(1)) type without C.