Hacker News new | ask | show | jobs
by garethrees 2756 days ago
In C you avoid signed integer overflow either by knowing that the result will be in range before applying an operation, or, as a last resort, by testing that the operation is defined before carrying it out. For example, if a and b are ints, then a + b is defined if (a >= 0 && b <= INT_MAX - a) || (a < 0 && b >= INT_MIN - a).

Additionally, some compilers can insert code to detect signed integer overflow at runtime. Clang has the -fsanitize=undefined flag [1].

[1] https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html

1 comments

Nope, that's the old way. Nowadays you do have access to the (un)signed add with carry (adc) builtins, which are the best way to provide an alternate method on overflow.
That is not portable.
no, gcc and clang do provide portable builtins. previously you had to use inline assembly, now it's trivial.
GCC and clang aren't the only C compilers on the planet.

Portable means being defined in the ISO C standard.

Why do you aspire to write "portable" code which you are referring to as code that conforms to the ISO C standard when most widely used compilers do not? What you are suggesting is extremely impractical, it is a matter between theory and practice. Conforming to the standard when the compiler itself does not is impractical. On top of that, these compilers are available on most platforms, and yours seem to be such an edge case that it is negligible, and you can make the necessary adjustments when and if it ever comes to that. It is likely that it will not. If it does, it is just a matter of one or two ifdefs. Personally I write code that conforms to the compiler, because in reality, from a practical point of view, that is all that really matters.
It is not impractical, past experience on doing library projects for mutiple POSIX platforms, where the number one requirement was that they had to be compilable by the system compilers, teached me the right way of writing portable C code.
Nope. Practically gcc and clang are available for all platforms, and for the rare cases someone uses another compiler or an old version you ifdef it out with the slow path. even ICC has the add/mult with carry overflow builtins.

The ISO C standard is hopelessly behind for decades. They don't even define a proper (unicode) string API (search, norm, utf8, fc) , constexpr, a memory model, ... and leave everything to the implementors.

I very much doubt that, specially since clang doesn't even cover all gcc supported architectures.

Additionally, being available doesn't mean it is the compiler one is allowed to use.

Apparently you haven't kept up with ISO C, C11 defined the memory model and portable threads. It is unfortunate that compiler vendors, specially your beloved gcc and clang disregard the security Annex K.