how to make gcc warn about arithmetic signed overflow

Andrew Haley aph@redhat.com
Thu Sep 26 17:41:00 GMT 2013


On 09/26/2013 03:29 AM, James K. Lowden wrote:
> On Tue, 24 Sep 2013 18:48:08 +0100
> Andrew Haley <aph@redhat.com> wrote:
> 
>>> 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 thought that's what you meant.  I was confused by "in your source"
> because of course source code doesn't overflow.

Well, overflows occur in terms of the virtual machine in which
standard C is specified.  So, IMO, it's not unreasonable to say that
the overflows are there in your source.

> You mean that a naïve rendering of the source code implies an
> overflow where none might exist in the actual emitted object code.

No, I don't.  If, say, you add two ints together and the sum is
greater than the maximum size, then a overflow occurs.  Whether this
overflow actually causes a machine overflow is another matter.

> And, presumably, the converse: that even if the source is written
> such that there logically can't be an overflow, the compiler might
> render object code that does.
> 
> As far as I'm concerned, that's neither here nor there.  When the
> compiler is done, there is object code that does execute on a real
> CPU and does -- on some architectures -- set an overflow bit in the
> status word for overflowing integer operations.

And what use would that be?  I can't think of any.  You'd have
erroneous programs that do overflow still not raising the overflow
flag because GCC helpfully removes the overflowing code.  It can do
that.  So you'd still have erroneous results.

Andrew.



More information about the Gcc-help mailing list