Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
EugenDueck opened this issue Apr 5, 2025 · 0 comments
Open

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

EugenDueck opened this issue Apr 5, 2025 · 0 comments

Comments

@EugenDueck
Copy link

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);
@EugenDueck EugenDueck changed the title Out-of-bounds access Out-of-bounds access actually already checked at compile Apr 5, 2025
@EugenDueck EugenDueck changed the title Out-of-bounds access actually already checked at compile Out-of-bounds access already checked at compile time Apr 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant