Is it ok to assume integer slices are sensibly aligned?

Unsafe Rust lets you do silly things like have oddly aligned slices:

let array = [1u16, 2, 3, 4, 5, 6, 7, 8];
let misalign: &[u16] = unsafe {
    let mut a = array.as_ptr() as *const u8;
    a = a.add(1);
    std::slice::from_raw_parts(a as *const u16, array.len() - 1)

Is it ok for my code to assume that other code won't do this? Or do I need to be more defensive? At the moment I simply have a debug_assert that checks the alignment is even.

This is UB to construct a slice with incorrect alignment. (But a debug assert to catch errors can only help!)

1 Like

Thanks! That makes my life easier. I'll keep the debug_assert because it's not doing any harm and as you say it may catch a bug.

Note: On release mode, even an assert checking the alignment with be optimized away because misaligned references are UB.



data must be non-null and aligned, even for zero-length slices.