Hacker News new | ask | show | jobs
by _flux 897 days ago
But you still need to pay attention to use overflow checking versions of functions when doing arithmetics, because in release mode regular integers are not overflow-checked at runtime, unless you explicitly enable -C overflow-checks=true—whichin my opinion would be a good default for many non-performance-critical applications.

Arguably it's the "pay attention" part that causes the bug in the first place, so I don't think the performance-oriented default was a good pick.

The issue is mitigated a bit by the remaining runtime array bounds checks, but I must wonder if those checks could be removed by the optimizer when it believes e.g. a variable can never be below a certain value.

2 comments

Apart from overflow checking in debug mode or with the right compile flag, rust also makes it a lot easier to do the right thing, e.g. 100u8.saturating_add(255) or even encoding it in the type system (`use std::num::Saturating; let mut x: Saturating<u8> = Saturating(128); x += 200; assert!(x == Saturating(255))`) (obviously you can also use Checking for explicit handling or Wrapping instead of Saturating). Meanwhile overflow handling in C/C++ is difficult, tedious and full of footguns caused by compiler optimizations.
It seems it's going to become easier to check them in C++26 with https://en.cppreference.com/w/cpp/numeric/add_sat and friends. Or if you want saturating integer types, you can find https://github.com/StefanHamminga/saturating (granted this does not seem maintained) or https://www.boost.org/doc/libs/master/libs/safe_numerics/doc... from boost for a checked integer type. https://github.com/mbeutel/slowmath gives you exception throwing checking.

I haven't tried that style in Rust—or in C++ for that matter—but is it truly much nicer than the options available for C++? Perhaps out-of-the-box experience is the winner there.

There are lints you can enable to enforce this, rather than just "pay attention".