Unsafe C function that changes more than its direct parameter

If you create a raw pointer with &mut planes[0] as *mut Plane, then that raw pointer is only allowed to access the first element, and it would be UB to access the other seven elements with the pointer. Using as_mut_ptr does not have this issue. This is because a raw pointer created from a reference can only access what you could have accessed through the reference, and a reference to the first element can't modify the other seven elements. You can see this by picking MIRI under the tools in this playground.

The compiler wont optimize your reads away unless you create a reference to the array between creating the raw pointer and passing the raw pointer to C.

// this is ok
let ptr = planes.as_mut_ptr();
call_c_func(ptr);
// this is not ok
let ptr = planes.as_mut_ptr();
let r = &mut planes[0]; // this invalidates the pointer
call_c_func(ptr);
5 Likes