3 ms·
It needs to do a check in order to decide to panic. C/C++ just allow undefined behavior which means they don't need to bounds check because the generated code i
by Shoop 6y ago
It needs to do a check in order to decide to panic. C/C++ just allow undefined behavior which means they don't need to bounds check because the generated code is allowed to have any behavior in this case (either the read just reads some random memory out of the heap or the kernel kills the process since it tried to access unmapped memory). In rust, panicing involves unwinding the stack. The compiler must generate code to do the bounds check and then also generate code to do the stack unwinding for the panic in the case where the bounds check fails.
- wahern 6y agoIn practice C code, especially well-written C code, will have most of the same bounds checks. It's not uncommon where a C programmer could safely omit a bounds check, but of course it's too often that the average C programmer mistakenly omits a bounds check or implements a bounds check wrong. See, e.g., the recent HN post, "Escaping VirtualBox 6.1", https://news.ycombinator.com/item?id=25795731 https://news.ycombinator.com/item?id=25795731 (https://secret.club/2021/01/14/vbox-escape.html https://secret.club/2021/01/14/vbox-escape.html).
- CyberRabbi 6y agoDo you have data to support your claim? My experience runs counter to your claim. Its fairly common for core performance-sensitive rust code to use “unsafe” to avoid unnecessary checks that the compiler cannot automatically elide.
- wahern 6y agoI was simply disputing the claim that C code will exclude bounds checks, relying on undefined behavior. Maybe I misunderstood the claim. I personally agree that the practical potential of Rust is oversold, especially in areas like kernels, low-level interfaces, etc. Bugs in those types of applications are often precisely at language and environmental interface boundaries, places where stronger type systems don't help. Similarly, AFAIU the current Rust toolchain doesn't do a stellar job at eliding as many bounds checks as theoretically possible, and I'm probably less optimistic than most about the pace of improvements on that front. It's just like with C++ or Java. It's easy to write a small microbenchmark or program where a compiler generates code that readily outclasses a typical, textbook C implementation. But that effect never seems to scale. People end up structuring their C++ and Rust programs the same way they'd structure a Python program, and even the best compilers can't turn lead into gold.