7

While reading the comments for this question, I came across a link to the comp.lang.c FAQ that shows a "careful addition function" which purportedly detects integer overflow:

int
chkadd(int a, int b)
{
    if (INT_MAX - b < a) {
        fputs("int overflow\n", stderr);
        return INT_MAX;
    }
    return a + b;
}

How does this not overflow if b == -1? If the assumption is that a and b are both positive, why make them int rather than unsigned int in the first place?

5
  • 2
    because INT_MAX - (-1) equals INT_MIN?
    – ddz
    Apr 28, 2016 at 15:34
  • 2
    Signed int might wrap: but it is undefined behaviour. Apr 28, 2016 at 15:34
  • 1
    Assumes a and b are positive. Useful for converting strings to int while checking for overflow. Apr 28, 2016 at 15:36
  • Don't spin your own, google "safeint library". Apr 28, 2016 at 15:40
  • @ddz In C, INT_MAX - (-1) is undefined behavior. A compiler can optimize that code to any answer including INT_MIN, 0, or 42 and still be a compliant compiler. Apr 28, 2016 at 16:32

2 Answers 2

4

OP has identified that INT_MAX - b may overflow, rendering the remaining code invalid for proper overflow detection. It does not work.

if (INT_MAX - b < a) {  // Invalid overflow detection

A method to detect overflow without UB follows:

int is_undefined_add1(int a, int b) {
  return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a);
}

why make them int rather than unsigned int in the first place?

Changing to unsigned does not solve the problem in general. The range of unsigned: [0...UINT_MAX] could be half of that of int: [INT_MIN...INT_MAX]. IOWs: INT_MAX == UINT_MAX. Such systems are rare these days. IAC, changing types is not needed as coded with is_undefined_add1().

1

Probably they just overlooked it. Additional links on the FAQ page seem to provide more correct code.

2
  • 1
    And those will fail if b == INT_MIN, but at least they mention it. I guess it's really just not as easy as they pretend, which is also my experience...
    – zennehoy
    Apr 28, 2016 at 15:44
  • That's what they also say in the "correct code": (Note: these functions all share one bug: they may fail if invoked on the largest negative integer, INT_MIN.). Apr 28, 2016 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.