Skip to content

unexpected behaviour for Vec<u8> index access in certain situation #141263

Open
@Rajakenhd

Description

@Rajakenhd

In my code I read a vec with std::fs::read(path) from a file and get the element at index 5 before further processing with the affected byte then being passed on by value to a function. When there are no changes to the ownership of said byte the variable will always be zero. (Workarounds like black_box. .to_owned() or pass by reference work but I still think it should work without since it can lead to unexpected behaviour).

I tried this code:

    let data = std::fs::read(path)?;
    let byte = data[5];
    Ok(MyStruct::new(data, byte))
    pub fn new(data: Vec<u8>, byte: u8) -> MyStruct {
        MyStruct {data, index_counter: 0, byte}
    }

I expected to see this happen: Value of data[5] should be 1 or depending on data some other value (but in this case data at index 5 is 1)

Instead, this happened: byte has value 0, as soon as some change to the ownership happens (either through dbg! or the other methods detailed above, or black_box is used the value of byte is 1)

Meta

Found in stable, but after testing seems to be present in beta and nightly too.
rustc --version --verbose:

rustc 1.87.0 (17067e9ac 2025-05-09)
binary: rustc
commit-hash: 17067e9ac6d7ecb70e50f92c1944e545188d2359
commit-date: 2025-05-09
host: x86_64-unknown-linux-gnu
release: 1.87.0
LLVM version: 20.1.1
Backtrace

 RUST_BACKTRACE=1 cargo build
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s

Metadata

Metadata

Assignees

No one assigned

    Labels

    S-needs-infoStatus: The issue lacks details necessary to triage or act on it.S-needs-reproStatus: This issue has no reproduction and needs a reproduction to make progress.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions