checking for overflow in C

Tim McDaniel mcdaniel at uicsrd.csrd.uiuc.edu
Wed May 10 05:05:57 AEST 1989


You can always do pre-checks, given <limits.h> or something like it:
        unsigned int a, b, c;
        ...
        assert(b == 0 || a <= UINT_MAX / b);
        c = a * b;
Similarly for other types and operations.  For unsigned adds, you can
do a post-check:
        c = a + b
overflowed if and only if c <= a or c <= b.

--

             Tim, the Bizarre and Oddly-Dressed Enchanter

Center for      |||  Internet, BITNET:  mcdaniel at uicsrd.csrd.uiuc.edu
Supercomputing  |||  UUCP:     {uunet,convex,pur-ee}!uiucuxc!uicsrd!mcdaniel
Research and    |||  ARPANET:  mcdaniel%uicsrd at uxc.cso.uiuc.edu
Development,    |||  CSNET:    mcdaniel%uicsrd at uiuc.csnet
U of Illinois   |||  DECnet:   GARCON::"mcdaniel at uicsrd.csrd.uiuc.edu"



More information about the Comp.lang.c mailing list