Skip to content

Writing uninitialized memory to a vector #4232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wyfo opened this issue Mar 18, 2025 · 3 comments
Closed

Writing uninitialized memory to a vector #4232

wyfo opened this issue Mar 18, 2025 · 3 comments

Comments

@wyfo
Copy link

wyfo commented Mar 18, 2025

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?

@RalfJung
Copy link
Member

Thanks for the report! Please have a look at this pinned issue and the discussion there. :)
#2518

@wyfo
Copy link
Author

wyfo commented Mar 18, 2025

Thank you for the information. I understood that validity of reference to uninitialized memory is still debated, and I agree with miri behavior here. However, in case of drop_in_place, safety documentation states

  • The value to_drop points to must be valid for dropping, which may mean it must uphold additional invariants. These invariants depend on the type of the value being dropped. For instance, when dropping a Box, the box’s pointer to the heap must be valid.

Would a slice with an item overwritten with uninitialized memory still be "valid for dropping"?

@RalfJung
Copy link
Member

That's a good question; it is tracked at rust-lang/unsafe-code-guidelines#394.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants