Change a variable through a raw pointer — which of the steps actually needs unsafe?
Through raw pointers, add 1 to the local variable x and then print its value.
Constraints:
- Make two raw pointers to
x: a*const i32for reading and a*mut i32for writing. - Write through the
*mut i32and read through the*const i32; the program prints6. - Wrap in
unsafeonly the operations that require it, and add a// SAFETY:comment. - Do not create an intermediate reference to
x.
fn main() {
let mut x = 5;
// your code here: two raw pointers to x,
// +1 through the *mut pointer, print through the *const pointer
}Write the implementation.
Creating the pointers with &raw const x and &raw mut x is safe; only *p += 1 and the read of *p go in unsafe. That block asserts each pointer is non-null, aligned and points to a live i32, with no reference to x alive meanwhile.
- Putting pointer creation inside
unsafe, as if taking an address were dangerous - Believing
unsafeswitches off borrow checking for the code inside the block - Thinking two raw pointers to one value fail to compile the way two
&mutdo
- Why can
&x as *const i32be wrong where&raw const xis fine, as for a packed struct field? - What does
p.add(2)do, and when is merely computing it undefined behaviour?
A raw pointer is just an address: the compiler promises nothing about it, so creating, copying, comparing or printing one is fine in ordinary code. Only dereferencing — reading or writing through the address — is dangerous, and that is what goes into unsafe. The code is built with rustc 1.99:
fn main() {
let mut x = 5;
let p_read = &raw const x; // *const i32: creating a pointer is safe
let p_write = &raw mut x; // *mut i32: a second pointer to x is not an error either
// SAFETY: both pointers come from the live local x, are non-null and aligned,
// and no reference to x exists while they are used.
unsafe {
*p_write += 1;
println!("{}", *p_read); // 6
}
let null: *const i32 = std::ptr::null();
println!("{}", null.is_null()); // true: inspecting a pointer is safe
}&raw const x and &raw mut x take the address of the place directly, without an intermediate reference; &x as *const i32 creates a reference first, which is not allowed, for example, for a misaligned field of a packed struct. The borrowing rules do not apply to raw pointers: the compiler accepts two *mut to one value, and keeping writes from happening under a live reference is the programmer's job. The unsafe block switches nothing off — type and borrow checking work inside it as usual; it only permits an operation whose safety the compiler cannot prove.