Skip to content

Out-of-bounds access already checked at compile time #266

@EugenDueck

Description

@EugenDueck

On https://github.com/mainmatter/100-exercises-to-learn-rust/blob/main/book/src/06_ticket_management/01_arrays.md , it reads:

Out-of-bounds access

If you try to access an element that's out of bounds, Rust will panic:

let numbers: [u32; 3] = [1, 2, 3];
let fourth = numbers[3]; // This will panic

This is enforced at runtime using bounds checking. It comes with a small performance overhead, but it's how
Rust prevents buffer overflows.\

However, this won't even compile:

error: this operation will panic at runtime
  --> exercises/06_ticket_management/01_arrays/src/lib.rs:28:22
   |
28 |         let fourth = numbers[x]; // This will panic
   |                      ^^^^^^^^^^ index out of bounds: the length is 3 but the index is 3
   |
   = note: `#[deny(unconditional_panic)]` on by default

Not sure if that's a recent change to rustc (I used 1.85.1), but I wanted to check it out, because I was surprised that the compiler wouldn't prevent this with an error.

The following will however not get caught by the compiler and indeed result in a runtime panic:

fn test(x: usize) {
    let numbers: [u32; 3] = [1, 2, 3];
    let fourth = numbers[x]; // This will panic
}
// ...
    test(3);

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