Skip to content

Writing uninitialized memory to a vector #4232

Closed
@wyfo

Description

@wyfo

I would expect the following code to be unsound:

let mut vec = vec![0u8, 1];
vec.as_mut_ptr().cast::<MaybeUninit<u8>>().write(MaybeUninit::uninit());

However, miri doesn't report anything. But Vec::drop uses ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)), and drop_in_place expects a pointer to a valid value, while the slice returned by slice_from_raw_parts_mut is invalid as it contains uninitialized memory, so it should be unsound, shouldn't it?

More curiously, this code also passes miri:

struct Droppable(u8);
impl Drop for Droppable {
    fn drop(&mut self) {}
}
let mut vec = vec![Droppable(0u8), Droppable(1)];
vec.as_mut_ptr().cast::<MaybeUninit<Droppable>>().write(MaybeUninit::uninit());

If we change impl Drop for Droppable to

impl Drop for Droppable {
    fn drop(&mut self) {
        dbg!(self.0)
    }
}

it fails because of uninitialized memory access.
However, although there is no access without dbg!, Drop::drop still takes a mutable reference which should be valid, while the first item of the vector is uninitialized. Shouldn't we have an error here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions