3 ms·
Writing C or C++ completely without undefined behavior is a daunting task. Signed integer over/underflow in particular is so easy to get wrong. Doing it manuall
by hermitdev 4y ago
Writing C or C++ completely without undefined behavior is a daunting task. Signed integer over/underflow in particular is so easy to get wrong. Doing it manually is a recipe for disaster. In C++, one can leverage "safe" or "checked" integer types that look and behave like regular signed ints, except they ensure no undefined behavior by checking potentially undefined operations before hand and appropriately handling the case where the checks fail by, e.g. throwing an exception or aborting.
What makes this more insidious is that you can't just look at a function in isolation, you need to look at how it's invoked to consider cases for UB. Consider: `int add(int x, int y) { return x + y; }` Does this have UB? `add(1, 1)` is fine. But what about `add(1, INT_MAX)` or `add(-1, INT_MIN)`? Yup, these are both UB.
Yes, developers should strive to eliminate UB. But, it's a hard problem. Tooling helps, but unfortunately the default settings for every compiler I'm aware of don't help. One really needs to use external tools and sanitizers, but let's be honest, the ergonomics of having to know about and use a separate tool, such as ubsan, isn't great. The tools are wonderful and need wider use, but they'd be of so much more value if they were integrated more tightly in the compiler/linker toolchains and on by default.