Skip to content

Document interaction between std::alloc and Box::{into_raw, from_raw} #53039

Closed
@FenrirWolf

Description

@FenrirWolf

The current documentation for Box::from_raw states that Boxes can only be made from raw pointers previously derived from Box::into_raw, but now that there are stable functions to directly access the allocator, one can imagine writing code like this:

use std::alloc::{alloc, Layout};
use std::ptr;

fn main() {
    let boxed = unsafe {
        let raw = alloc(Layout::from_size_align(4, 4).unwrap()) as *mut i32;

        ptr::write(raw, 42);

        Box::from_raw(raw)
    };

    println!("{}", boxed); // prints `42` with `Box`'s `Display` impl

    // `boxed` gets dropped here instead of deallocating directly with `std::alloc::dealloc`
}

Is such code sound? Or is Box's allocator still considered unspecified?

Metadata

Metadata

Assignees

No one assigned

    Labels

    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