std-method

Preserve provenance with addr and with_addr

An address is an integer location; provenance describes the pointer’s association with memory and its allowed uses. addr extracts the address without exposing provenance. with_addr changes an address using an existing pointer as the provenance source. Neither grants access to a different allocation. These strict-provenance methods are stable from Rust 1.84; precise aliasing semantics remain under development. Expected stdout (not executed): 28 Common mistake: Restoring an addr result with an integer-to-pointer cast and assuming that restores access rights.

Formal Syntax & Structure

rust syntaxrust
p.with_addr(address: usize)

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let items = [14_u8, 28, 42];    let p = items.as_ptr();    let address = p.wrapping_add(1).addr();    let q = p.with_addr(address);    // SAFETY: q retains p's provenance and points at a live initialized byte of items.    println!("{}", unsafe { *q });}
Rust Reference