1

Possible Duplicate:
Best way to detect integer overflow in C/C++

I'm a beginner to C programming and I wrote a program to read long int byte at a time and print out at the end of a whitespace. I need to configure it to catch overflow/underflow using LONG_MAX and LONG_MIN in limits.h library. I'm not allowed to cast up to anything higher than long int, and also it should detect overflow for negative numbers too. Here's my code:

int main(void)
{
    int c;
    int state;
    long int num = 0;

    while((c = getchar()) != EOF)
    {
        switch(state)
        {
            case 0:
            {
                if (isspace(c))
                {
                    //do nothing;
                }
                else
                {
                    state = 1;
                    num = 10 * num + (c - '0');
                }
                break;
            }

            case 1:
            {
                if (isspace(c))
                {
                    printf("%ld\n", num);
                    num = 0;
                    state = 0;
                    break;
                }

                num = 10 * num + (c - '0');

                if (num < LONG_MIN || num > LONG_MAX)
                {
                    printf("overflow\n");
                    break;
                }
                break;
            }
        }
    }
    return 0;
}

The part where if (num < LONG_MIN || num > LONG_MAX) doesn't seem to work because, for example, if the input is LONG_MAX+1, it overflows and become LONG_MIN and vice versa when underflows.

Community
  • 1
  • 1
SharkTiles
  • 585
  • 3
  • 9
  • 22

1 Answers1

0

Easiest way to detect overflow is to check to make sure "num" is always getting larger than what is was before.

oldnum = num;
num = 10 * num + (c - '0');

if (num < oldnum)
{
    // overflow!
    printf("overflow\n");
}

There's a few edge conditions to consider, but the above should mostly work regardless of whether num is signed, unsigned, or whatever it's width is.

selbie
  • 100,020
  • 15
  • 103
  • 173
  • This idea is dangerous. First, overflow might raise a signal and you'd never have a chance to check. Then your assumption only works for overflow of addition or substraction, not for multiplication. – Jens Gustedt Jun 17 '12 at 07:26
  • @JensGustedt - can you provide code that demonstrates overflow raising a signal as a result of performing integer arithmetic? – selbie Jun 17 '12 at 07:44
  • If you have gcc as a compiler using the option `-ftrapv` will add code for that. gcc also lets you have the inverse, with `-fstrict-overflow` it assumes that your arithmetic will never overflow. With that your check might be optimized out because of the compiler assuming that it is a dead branch. – Jens Gustedt Jun 17 '12 at 09:50
  • This is plain wrong. It works for unsigned but not for signed. – R.. GitHub STOP HELPING ICE Jun 17 '12 at 14:56