What is the exact difference between "aligned to" and the alignment of a raw pointer?

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 to mem::align_of::<T>()).

And in Behavior considered undefined - The Rust Reference

For instance, if ptr has type *const S where S has an alignment of 8, then ptr 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?

Yes, your understanding is correct. The first quote from the reference is about align_of::<*const T> (a property of the pointer type), while the other quotes are about the address contained in a pointer value (and whether it matches the alignment of the pointee type.)

3 Likes

I’m not sure if you can rely on this distinction in other writing, as it is quite subtle and other authors might not use language that precisely. Instead, looking at the wider context where “aligned”/“alignment” is mentioned is probably a better guide, keeping in mind the basic definition of memory alignment:

k-alignment/aligned refers to a memory address a where a ≡ 0 (mod k).

In the case of a pointer/reference type, though, there are two different memory addresses that the author might be referring to:

  1. The address of the pointee, i.e. the value stored within the pointer
  2. The memory location where the pointer itself is stored

This leads to an ambiguity in a lot of documentation which can only be resolved by using “common sense”— Something that can be quite hard to come by despite its name.

1 Like