Struct contains a u32/u64; guarantees that struct is aligned to 32/64 bits?

#1
  1. I ahve a struct that has a field that is a u32 (or u64). Does this guarantee that allocations of the struct will always be aligned to 4bytes (or 8 bytes) ?
0 Likes

#2

The alignment of your struct will mainly depend on your target architecture, therefore, the actual fields of a struct does have that much effect on alignment. Further on the Rust-compiler is per default allowed to optimze a struct’s layout.
I think the only way to exactly determine a structs memory layout is using the #[repr(C)] attribute or if you are very barve you could use #[repr(packed)]. See the Rustonnomicon’s Data Layout section for further information.

0 Likes

#3

A struct will always be at least as aligned as each of its fields (unless you use repr(packed)). This is necessary to make it safe to get references to those fields.

More precise guarantees are not provided for repr(rust).

0 Likes

#4

u64 is not necessarily 64-bit aligned – on i686, std::mem::align_of::<u64>() == 4 bytes!

If you really want 64-bit alignment, use #[repr(align(8))] on your struct.

2 Likes