Alignment and packing


#1

I am totally new to rust and also to low level programming. I am reading different books on memory management.

I would like to ask how rust puts variables on the memory ?

in c++ you could put same sized types together and the compiler aligns them together and puts padding as well on the memory. How is this compared to rust ?

would the following make a difference in rust ?

Unaligned:
struct UnalignedPacking {
	var1: u32,
	var2: f32,
	var3: u8,
	var4: i32,
	var5: bool,
	var6: char
}
Aligned:
struct AlignedPacking {
	var1: u32,
	var2: f32,
	var3: i32,
	var4: char,
	var5: u8,
	var6: bool
}

#2

You’ll find this interesting: http://camlorn.net/posts/April%202017/rust-struct-field-reordering.html

The short of is that repr(rust) (default layout) is unspecified and the above blog talks about minimizing alignment gaps/padding due to the naive declaration order layout. As of Rust 1.18, the layout is done to minimize the gaps (as that blog mentions).


#3

thanks this is really helpfull