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.

https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=f46cf6876e0eb3ab672181ebd2683ad3

3 Likes

Reference: https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety

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

3 Likes