Summary - Memory layout
- Rust course
- Expert
- Lesson 12/46
- 5 min
Combine repr, alignment and ZST to write a memory analysis.
Memory layout summary
The default layout gives the compiler freedom to reorder fields; repr(C) guarantees order and C compatibility, repr(transparent) makes a wrapper the same as its inner type, repr(u8) fixes an enum's discriminant. Alignment decides which addresses a value can sit at and produces padding. ZSTs take no room; niche optimization lets enums like Option use no extra bytes. Code relying on the layout must always use an explicit repr.
Reordering by hand
When repr(C) is needed, the programmer reduces the padding. The rule: order fields by alignment from largest to smallest:
#[repr(C)]
struct Kotu { a: u8, b: u64, c: u8 } // 24
#[repr(C)]
struct Iyi { b: u64, a: u8, c: u8 } // 16: 8 + 1 + 1 + 6 paddingClippy's clippy::pedantic group and cargo +nightly rustc -- -Zprint-type-sizes help find large padding.
Practice Reduce the padding
Write the types #[repr(C)] struct Kotu and #[repr(C)] struct Iyi above. Print the size_of of both separated by a space.
Starter code
use std::mem::size_of;
fn main() {
// buraya yaz
}Sample solution
#![allow(dead_code)]
use std::mem::size_of;
#[repr(C)]
struct Kotu {
a: u8,
b: u64,
c: u8,
}
#[repr(C)]
struct Iyi {
b: u64,
a: u8,
c: u8,
}
fn main() {
println!("{} {}", size_of::<Kotu>(), size_of::<Iyi>());
}Expected output
24 16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is <code>#[repr(C)] struct { a: u8, b: u64, c: u8 }</code> 24 bytes?
- An error
- It's 16 bytes
- 7 bytes of padding after a and 7 after c: 1 + 7 + 8 + 1 + 7 Correct answer
- Fields are 8 bytes each
Explanation: b must be 8-aligned, and the total size must be a multiple of 8. Writing the fields in the order b, a, c brings it down to 16 bytes.
2 Largest to smallest
#[repr(C)]
struct Iyi {
____,
a: u8,
c: u8,
}
#[repr(C)]
struct Iyi {
b: u64,
a: u8,
c: u8,
}
Explanation: Putting the field with the largest alignment first reduces padding.
3 Group summary
| Term | Meaning |
|---|---|
repr(Rust) |
Free ordering |
repr(C) |
Preserved order |
ZST |
Zero bytes |
Niche |
Free Option |