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?

Community
  • 1
  • 1
zennehoy
  • 6,405
  • 28
  • 55

2 Answers2

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().

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

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

  • 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 '16 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.). – user3078414 Apr 28 '16 at 16:06