Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust vector's `get_unchecked` still performs bounds checking?

Learning rust and tried running this code (https://godbolt.org/z/b6Yrj3dfx):

fn main() {
    let foo = vec![1,2,3];

    println!("Value: {}", unsafe { foo.get_unchecked(3) });
}

Output:

thread 'main' panicked at core/src/panicking.rs:221:5:
unsafe precondition(s) violated: slice::get_unchecked requires that the index is within the slice
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
Program terminated with signal: SIGSEGV

I was expecting the program to print out some random value just like in C/C++, but from the error message it seems that it’s still doing bounds checking?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Documentation of get_unchecked:

Returns a reference to an element or subslice, without doing bounds checking.

What gives?

>Solution :

By using unsafe, you promised to not call get_unchecked() with an out of bounds index. You broke this promise. You invoked Undefined Behavior. Now Rust is free to do whatever it wants – and that includes panicking (in fact, a deterministic panic is probably the best outcome you can expect in this scenario). This is why Rust is allowed to do what it does.

As for why it does what it do, the reason is to have a safety net. In debug builds, Rust will make extra assertions to help you detect UB in your code. In release mode, this will be disabled, so the code can be the most performant possible.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading