News for hackers. Stuff that matters.
Re:Catching Integer Overflows in C by JoachimSchipper on Tuesday August 02, 2011 @07:58AM (#2836794)
I'm not a fan of this approach - did you notice that addition, for instance, just returns 1(!) instead of overflowing?

The proper way to do this is still

    if (a > UINT_MAX - b)
        errx(1, "Too large.");
    a += b;
and variants.
Re:Catching Integer Overflows in C by apgwoz on Tuesday August 02, 2011 @08:25AM (#2836856)
And for INT_MIN? The c-faq (http://c-faq.com/misc/sd26.html) says that this approach fails in that case. Is your suggestion to just avoid INT_MIN? If so, that works. :)
Re:Catching Integer Overflows in C by JoachimSchipper on Tuesday August 02, 2011 @10:52AM (#2837309)
To be honest, my suggestion is to avoid signed integers, or at least negative signed integers (beyond perhaps -1 for signalling errors). I find that I almost never need them, and unsigned integers are much nicer to work with.
Re:Catching Integer Overflows in C by apgwoz on Tuesday August 02, 2011 @12:31PM (#2837702)
That's an interesting perspective, and one that probably works out in practice most of the time. Integration with other libs is the place I'm thinking where it doesn't, but it seems simple, and rather trivial in many cases to do the conversion to signed integers before making the library call. Of course, if you're taking advantage of the extra positive values and need a signed int, I think you're shit out of luck.
Re:Catching Integer Overflows in C by rplnt on Tuesday August 02, 2011 @08:28AM (#2836863)
I've used this approach in one of my school assignments. The result (macros) weren't so nice but I think they've worked. It was few years back so I'm not so sure now.

https://github.com/rplnt/personal/blob/master/C/fractions/zl...

Re:Catching Integer Overflows in C by Estragon on Tuesday August 02, 2011 @08:50AM (#2836910)
The return value of 1 is strange, but superficial. It's easy enough to replace that with arbitrary behavior. The advantage of the approach in the OP is that it is more agnostic about the types involved, leading to more flexible code.