[PLUG] detecting integer overflow in C

Russell Senior russell at personaltelco.net
Sat Aug 18 23:42:48 UTC 2007


>>>>> "Keith" == Keith Lofstrom <keithl at kl-ic.com> writes:

Keith> Is there an easy way to detect integer overflow in C?

Keith> In other words, if I add 1 to INTMAX, I will probably get an
Keith> overflow and the result will be a negative number on a two's
Keith> complement machine.

Keith> The X86 processor (and most other processors) has a hardware
Keith> status bit that gets set when an overflow happens; how do I
Keith> access that in a C program?  Is there a library call or a
Keith> conditional I can test?

I'll start by saying "I don't know the answer to your question".
However, I did think of this, fwiw.  If it is really just a case of
adding one, then the test is easy, you just check the value before you
add one.  Since that is so easy, and you aren't stupid, I'll assume
that the problem is more complex than that, more like N + M where N
and M are arbitrary.  One solution to getting the hardware status bit
might be to use inline assembly, which gcc supports, to look at the
status bit.  Another solution might be to use GMP
<http://gmplib.org/>, a land where values never overflow (as long as
there is memory to represent them).

I googled glibc integer overflow and didn't see anything particularly
relevant in the first couple pages of hits.  Maybe there is something
in the glibc documentation.

FWIW.


-- 
Russell Senior, Secretary
russell at personaltelco.net



More information about the PLUG mailing list