Hacker News new | ask | show | jobs
by Asooka 1203 days ago
One big difference between unsafe Rust and C is that C compilers have flags to turn off the UB, so you have a lot less mental load when writing it. You go from e.g. "if this index calculation overflows, we may read from outside the array, because the bounds check was deleted" to "if this index calculation overflows, we may read from the wrong index, but never outside of the array bounds". UB is Damocles's sword and the speed gains are usually not worth it. With UB your program can enter a buggy state that you cannot detect, because "it cannot happen". Without UB, your program can still enter a buggy state, but you can detect it and potentially recover or crash immediately before even more things go wrong.
4 comments

Very true and worth evangelizing to others. I have unknowingly violated -fstrict-aliasing in some part of my code only to discover later that it is benign at -O0 and metastasized at -O3.

This freaks me out the most in networking code, where there is all kinds of casting of structs (esp. if you blindly copy-paste examples from StackOverflow) and performance usually matters. Rust has inspired me to take more time to profile C code to see whether strict aliasing (strict overflow, etc.) actually make a significant enough improvement to merit the UB-risk, review time, and acid in the stomach.

Some flags to turn off some UB, and not all of them have those flags.
Are all the UBs defined/documented/catalogued somewhere?
Which compiler flags do I use to turn off UB?