std-method

Distinguish wrapping arithmetic from memory access

wrapping_add can compute an address outside the allocation without itself performing a memory access. It does not acquire permission to access that address. In this example the pointer is brought back to the original element before reading; the live allocation remains unchanged. Expected stdout (not executed): 11 Common mistake: Reading the intermediate out-of-bounds pointer because wrapping_add is a safe method.

Formal Syntax & Structure

rust syntaxrust
p.wrapping_add(count)

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let items = [11_i32, 22];    let base = items.as_ptr();    let outside = base.wrapping_add(10);    let back = outside.wrapping_sub(10);    // SAFETY: back returns to the first live initialized element; no conflicting access.    println!("{}", unsafe { *back });}
Rust Reference