Skip to content

uninitialized bytes in a local variable are not caught #2732

Closed
@oconnor663

Description

@oconnor663

Playground link

use std::ptr::copy_nonoverlapping;

#[derive(Debug, PartialEq)]
#[repr(C)]
struct Foo {
    x: u8,
    // uninitialized padding goes here
    y: u16,
}

fn main() {
    let foo = Foo { x: 1, y: 2 };

    // Copy the bytes of foo to a buffer, including the uninitialized padding byte.
    let mut buf = [0u8; 4];
    unsafe {
        copy_nonoverlapping(&foo as *const Foo as *const u8, buf.as_mut_ptr(), 4);
    }

    // Copy the buffer back to foo2. This passes Miri.
    let mut foo2 = Foo { x: 0, y: 0 };
    unsafe {
        copy_nonoverlapping(buf.as_ptr(), &mut foo2 as *mut Foo as *mut u8, 4);
    }
    assert_eq!(foo, foo2);

    // Uncommenting any of the following lines fails Miri.
    // drop(buf);
    // buf = buf;
    // buf[1];
}

This is similar to #2518 (uninitialized value behind a reference), except here the uninitialized value is in a local variable.

Is it expected that Miri doesn't currently trigger on this code? Any thoughts about whether this is likely to be UB in the future?

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