Dereferencing Raw Pointers

Creating pointers is safe, but dereferencing them requires unsafe:

  1. fn main() {
  2.     let mut s = String::from("careful!");
  3.     let r1 = &raw mut s;
  4.     let r2 = r1 as *const String;
  5.     // SAFETY: r1 and r2 were obtained from references and so are guaranteed to
  6.     // be non-null and properly aligned, the objects underlying the references
  7.     // from which they were obtained are live throughout the whole unsafe
  8.     // block, and they are not accessed either through the references or
  9.     // concurrently through any other pointers.
  10.     unsafe {
  11.         println!("r1 is: {}", *r1);
  12.         *r1 = String::from("uhoh");
  13.         println!("r2 is: {}", *r2);
  14.     }
  15.     // NOT SAFE. DO NOT DO THIS.
  16.     /*
  17.     let r3: &String = unsafe { &*r1 };
  18.     drop(s);
  19.     println!("r3 is: {}", *r3);
  20.     */
  21. }

This slide should take about 10 minutes.

It is good practice (and required by the Android Rust style guide) to write a comment for each unsafe block explaining how the code inside it satisfies the safety requirements of the unsafe operations it is doing.

In the case of pointer dereferences, this means that the pointers must be valid, i.e.:

  • The pointer must be non-null.
  • The pointer must be dereferenceable (within the bounds of a single allocated object).
  • The object must not have been deallocated.
  • There must not be concurrent accesses to the same location.
  • If the pointer was obtained by casting a reference, the underlying object must be live and no reference may be used to access the memory.

In most cases the pointer must also be properly aligned.

The “NOT SAFE” section gives an example of a common kind of UB bug: *r1 has the 'static lifetime, so r3 has type &'static String, and thus outlives s. Creating a reference from a pointer requires great care.