how to make gcc warn about arithmetic signed overflow

Andrew Haley
Tue Sep 24 17:48:00 GMT 2013

On 09/23/2013 11:00 PM, James K. Lowden wrote:
> On Mon, 23 Sep 2013 20:48:23 +0100
> Andrew Haley <> wrote:
>> On 09/23/2013 08:38 PM, Dave Allured - NOAA Affiliate wrote:
>>> I believe the CPU overflow flag is updated after most integer
>>> arithmetic instructions.  Does GCC have any facility for checking
>>> this flag after each integer operation?  This would be a runtime
>>> check, of course, not a compile time check.
>> It wouldn't help with optimized code.  GCC reorganizes code, and it
>> assumes that overflow doesn't happen.  GCC inserts some arithmetic
>> instructions while optimizing and deletes others.  So, even if an
>> overflow happens in your code, it doesn't necessarily happen at
>> runtime.
> Could you unpack that a bit?  Regardless of optimization, the CPU, not
> the compiler, executes the ADD or MUL operation, or whatever, and sets
> or does not set the overflow bit accordingly, right?  Why can't the
> compiler generate code that senses that, and raises a runtime error?

Because the compiler does a lot of rewriting.  There is not a one-to-
one mapping between operations in your source program and
instructions.  An operation might occur in your program but not in the
object code.  For example, say you do this:

   int n = m + BIG_NUMBER;
   return n - BIG_NUMBER;

There is an overflow in your source, but not in the object code.  So
no trap will occur.

> I've written a lot of SAFE_CAST macros that check the return of sizeof
> or strlen(3) before casting it to an int and assigning the result to
> something that *must* be an int.  That code is terribly inefficient,
> clumsy to read, noise on the screen, really.  But made necessary IMO
> because the compiler conceals what the processor reports.  

I'm not quite sure what you mean by this.  Why would you want to cast
it to an int, anyway?  Desperately short of space?


More information about the Gcc-help mailing list