In Type layout - The Rust Reference, the alignment of a raw pointer type is defined as:
Pointers to sized types have the same size and alignment as
usize
.
That is any pointer type, for example, * const T
or * mut T
, has the same alignment as that of std::mem::align_of::<usize>()
, whatever T
is any sized type.
However, in the document std::ptr - Rust
Valid raw pointers as defined above are not necessarily properly aligned(where “proper” alignment is defined by the pointee type, i.e.,
*const T
must be aligned tomem::align_of::<T>()
).
And in Behavior considered undefined - The Rust Reference
For instance, if
ptr
has type*const S
whereS
has an alignment of 8, thenptr
must be 8-aligned or else(*ptr).f
is "based on an misaligned pointer".
I notice the subtle difference in these wordings, they use "aligned" and "alignment", respectively.
What does "a pointer aligned to xxx or xxx-aligned" mean? My understanding is, that assuming the pointer is of type * const/mut T
, the address pointed to by the pointer should satisfy the alignment of T
. Is this the right understanding?
For example:
fn main(){
let c = 0u8;
let ptr = &c as * const u8 as * const u16;
}
Assume the address of c
is 0x1
, since the type of ptr
is * const u16
, which is aligned to 2
(the alignment of pointee type u16
), the address 0x1
cannot satisfy the alignment requirement, hence ptr
is a misaligned pointer, right?