Skip to content

Safety comment in std::ptr::NonNull::dangling code was invalidated by a refactoring #132004

Closed
@tifv

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsLibs-SmallLibs issues that are considered "small" or self-containedT-libsRelevant to the library team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions