Repository navigation
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
hanna-kruppe commentedon Oct 21, 2024
The standard library can rely on its own undocumented behavior (unlike user code). It's also just a documentation oversight that
ptr::danglingdoesn't state that its result is non-null -- that is the entire reason why it exists. It would be good to fix the documentation and that should be uncontroversial. Updating the comment inNonNull::danglingdoesn't have to be blocked on that, though.Noratrieb commentedon Oct 21, 2024
Feel free to open a PR changing the SAFETY comment and docs.
Rollup merge of rust-lang#132065 - tifv:dangling-docs, r=Noratrieb
Unrolled build for rust-lang#132065