Closed
Description
This is an example code snippet for std::ptr::write_bytes
:
use std::ptr;
let mut v = Box::new(0i32);
unsafe {
// Leaks the previously held value by overwriting the `Box<T>` with
// a null pointer.
ptr::write_bytes(&mut v as *mut Box<i32>, 0, 1);
}
// At this point, using or dropping `v` results in undefined behavior.
// drop(v); // ERROR
// Even leaking `v` "uses" it, and hence is undefined behavior.
// mem::forget(v); // ERROR
// In fact, `v` is invalid according to basic type layout invariants, so *any*
// operation touching it is undefined behavior.
// let v2 = v; // ERROR
unsafe {
// Let us instead put in a valid value
ptr::write(&mut v as *mut Box<i32>, Box::new(42i32));
}
// Now the box is fine
assert_eq!(*v, 42);
This example writes a null pointer to a box, which (verbatim!) "is invalid according to basic type layout invariants". Then it incorrectly states that this is fine as long as we do not "touch" the box, while really this is already UB. This looks like a documentation bug to me.
As a side note: why is Unique<T>
not intended to be stabilized? The strong aliasing guarantees could be useful in someone's unsafe code.
Metadata
Metadata
Assignees
Labels
Area: raw pointers, MaybeUninit, NonNullCategory: This is a bug.Call for participation: Help is requested to fix this issue.Call for participation: Medium difficulty. Experience needed to fix: Intermediate.Call for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.