Why isn't this out-of-bounds error detected at compile-time?

Viewed 91

I've just started coding in rust for a few days now and have stumbled upon this case here that I don't understand

struct Foo {
    arr: [u8; 5]
}

fn main() {
    let foo = Foo{ arr: [0; 5] };
    let bar = &foo;
    println!("{}", bar.arr[100]);
}

Why does this code compile? Can't the compiler see that there is an out-of-bounds error there? It can detect it when i try to print foo.arr[100], so what gives?

1 Answers

In general, not all errors that could be detected at compile-time will be reported to the compiler. In this case though, it should be detected since Rust 1.60 and earlier will report this problem, but Rust 1.61 and 1.62 will not:

$ cargo +1.60 build
   Compiling mycrate v0.1.0 (/rust-tests)
error: this operation will panic at runtime
   --> src/main.rs:133:20
    |
133 |     println!("{}", bar.arr[100]);
    |                    ^^^^^^^^^^^^ index out of bounds: the length is 5 but the index is 100
    |
    = note: `#[deny(unconditional_panic)]` on by default
$ cargo +1.61 build
   Compiling mycrate v0.1.0 (/rust-tests)
    Finished dev [unoptimized + debuginfo] target(s) in 0.78s

This has already been reported as issue #98444: Taking a shared reference of an array suppresses the unconditional_panic lint. You can downgrade your toolchain but hopefully it is resolved soon.

Related