std-method
Check pointer alignment with is_aligned
Alignment describes the address boundary required by a type. An alignment test says nothing about whether storage exists at the address. Here an explicitly aligned type makes the result independent of the usual alignment of integer types. Expected stdout (not executed): aligned: true; shifted: false; value: 7 Common mistake: Dereferencing a pointer solely because is_aligned returned true.
Formal Syntax & Structure
rust syntaxrust
p.is_aligned() -> boolWorking Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { #[repr(align(8))] struct Aligned(u8); let value = Aligned(7); let p = &raw const value; assert!(p.is_aligned()); let shifted = p.cast::<u8>().wrapping_add(1).cast::<Aligned>(); assert!(!shifted.is_aligned()); println!("aligned: true; shifted: false; value: {}", value.0);}