Skip to content

Documentation for mem::forget implies that it may invalidate raw pointers to heap allocations #79320

Description

@fleabitdev

The doc comment for mem::forget currently reads:

Any resources the value manages, such as heap memory or a file handle, will linger forever in an unreachable state. However, it does not guarantee that pointers to this memory will remain valid.

The second sentence was introduced in #53503, with this rationale:

it's not obvious mem::forget does not guarantee leaking of memory: memory of stack-allocated objects and values partially moved out of Box will still be freed

In other words, it's intended to be a warning about these two footguns:

let byte = 42_u8;
let raw_ptr = &byte as *const u8;
std::mem::forget(byte);
let forty_two = unsafe { *raw_ptr };

let raw_ptr;
{
    let boxed_byte = Box::new(42u8);
    raw_ptr = &*boxed_byte as *const u8;
    std::mem::forget(*boxed_byte);
}
let forty_two = unsafe { *raw_ptr };

To me, the current language is too broad. It implies that heap allocations owned by a value passed to mem::forget may be invalidated. For example, it implies that the following code is unsound:

let s = format!("example");
let s_ptr = s.as_ptr();
std::mem::forget(s);
let lowercase_e = unsafe { *s_ptr };

Opening an issue rather than a PR because I'm not sure how best to rephrase this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and tools

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions