rust-lang / rust-lang/rust

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

Open
#141,263 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

S-needs-info S-needs-repro
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by turning the std::fs::read and Vec index-access snippets into a minimal reproducible example, then compare behavior on stable, beta, and nightly using the stated rustc version. Done means a minimized reproduction with the observed value and enough evidence to guide a compiler investigation.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.