Safety comment in std::ptr::NonNull::dangling
code was invalidated by a refactoring #132004
Description
The implementation of the std::ptr::NonNull::dangling
function looked like this:
pub const fn dangling() -> Self {
// SAFETY: mem::align_of() returns a non-zero usize which is then casted
// to a *mut T. Therefore, `ptr` is not null and the conditions for
// calling new_unchecked() are respected.
unsafe {
let ptr = crate::ptr::invalid_mut::<T>(mem::align_of::<T>());
NonNull::new_unchecked(ptr)
}
}
until a recent change (b58f647) made it into this:
pub const fn dangling() -> Self {
// SAFETY: mem::align_of() returns a non-zero usize which is then casted
// to a *mut T. Therefore, `ptr` is not null and the conditions for
// calling new_unchecked() are respected.
unsafe {
let ptr = crate::ptr::dangling_mut::<T>();
NonNull::new_unchecked(ptr)
}
}
The code has changed, but the comment has not, and is now unrelated to the code.
Furthermore, it is unclear how to rewrite this comment correctly. The documentation of std::ptr::dangling_mut
function only guarantees that it “Creates a new pointer that is dangling, but well-aligned”. However, the documentation of std::ptr
module defines a dangling pointer with “We say that a pointer is "dangling" if it is not valid for any non-zero-sized accesses. This means out-of-bounds pointers, pointers to freed memory, null pointers, and pointers created with NonNull::dangling
are all dangling”. Since a dangling pointer can technically be null, the fact that std::ptr::dangling_mut
returns a non-null pointer is an undocumented behaviour. This means that the safety of std::ptr::NonNull::dangling
hinges on an undocumented behavior of another function.
Activity