A raw pointer stores a memory address without the lifetime or ownership information attached to a Rust reference. Because the compiler cannot validate whether its target is valid, dereferencing it requires an unsafe block and leaves those safety checks to the programmer. section 3.1.1 section 3.1
Raw pointers support low-level operations needed at language boundaries:
- Use *const T for an immutable target and *mut T for a mutable target, paralleling immutable and mutable references. section 3.1.1
- Obtain a pointer to a Vec<u8> buffer with as_ptr; creating the pointer is safe, but reading through it is unsafe. section 3.1.1
- Read successive elements with pointer offset arithmetic, while ensuring that the pointer and length describe valid memory. section 3.1.1
- Use null checks, offset_from, and std::slice::from_raw_parts when interpreting nested C structures or externally owned buffers. section 4.4.2
Reading a byte buffer
A vector can pass its buffer pointer and length to a function such as read_u8_slice. The function loops over the length and dereferences slice_p.offset(index as isize) inside unsafe, printing each byte.
