Skip to content

std::ptr::write_bytes should clearly explain safety and validity invariants #84184

Closed
@lokegustafsson

Description

@lokegustafsson

This is an example code snippet for std::ptr::write_bytes:

use std::ptr;

let mut v = Box::new(0i32);

unsafe {
    // Leaks the previously held value by overwriting the `Box<T>` with
    // a null pointer.
    ptr::write_bytes(&mut v as *mut Box<i32>, 0, 1);
}

// At this point, using or dropping `v` results in undefined behavior.
// drop(v); // ERROR

// Even leaking `v` "uses" it, and hence is undefined behavior.
// mem::forget(v); // ERROR

// In fact, `v` is invalid according to basic type layout invariants, so *any*
// operation touching it is undefined behavior.
// let v2 = v; // ERROR

unsafe {
    // Let us instead put in a valid value
    ptr::write(&mut v as *mut Box<i32>, Box::new(42i32));
}

// Now the box is fine
assert_eq!(*v, 42);

This example writes a null pointer to a box, which (verbatim!) "is invalid according to basic type layout invariants". Then it incorrectly states that this is fine as long as we do not "touch" the box, while really this is already UB. This looks like a documentation bug to me.

As a side note: why is Unique<T> not intended to be stabilized? The strong aliasing guarantees could be useful in someone's unsafe code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-raw-pointersArea: raw pointers, MaybeUninit, NonNullC-bugCategory: This is a bug.E-help-wantedCall for participation: Help is requested to fix this issue.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions