Course contentsShow
← Rust
Lesson 269 of 1,9103. Borrowing and ReferencesFree lesson

Analyzing Pointer Alignment

Ensure references point to memory aligned with the underlying architecture.

In this lesson, you will learn why computer architectures require data to sit at specific memory addresses and how to ensure your Rust references respect those rules.

The Physical Reality of Memory

Computers don't access RAM one byte at a time; they typically grab data in "chunks" (like 4 or 8 bytes). Because of this, CPU hardware is optimized to read data that starts at an address divisible by its own size. If an integer is 4 bytes, the CPU wants it stored at an address that is a multiple of 4.

When a pointer points to an address that satisfies this requirement, we say the pointer is aligned. If you try to access data at an "unaligned" address (e.g., an 8-byte u64 starting at an odd address), your program will either crash, trigger a hardware exception, or perform significantly slower because the CPU has to do two memory fetches to assemble your value.

Rust's Guarantee

In safe Rust, the compiler automatically handles alignment for you. When you create a struct or a stack-allocated variable, the compiler ensures the memory is laid out so every field starts at an appropriate boundary.

However, when you step into unsafe blocks and raw pointers, you take on the responsibility of maintaining this alignment. Consider this example:

let data: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
let ptr = data.as_ptr();

// If we cast this to a pointer to a u64, we must ensure 'ptr' 
// is aligned to 8 bytes, or this next line is Undefined Behavior!
unsafe {
    let u64_ptr = ptr as *const u64;
    // We would need to verify alignment here: 
    // assert!(u64_ptr.is_aligned());
    let val = *u64_ptr;
}

If ptr happens to point to an address that isn't a multiple of 8, dereferencing u64_ptr is invalid. In Rust, you can check alignment using the .is_aligned() method on a pointer. When working with raw pointers or custom memory allocators, always verify that your pointers match the alignment requirements of the type you intend to read.

Key Takeaway: Alignment is a hardware requirement for performance and stability; when using raw pointers, you must ensure the address is a multiple of the type’s alignment to avoid undefined behavior.