GCC Undefined Behavior Sanitizer

via Digitalmars-d digitalmars-d at puremagic.com
Sun Oct 19 02:56:43 PDT 2014


On Sunday, 19 October 2014 at 08:37:54 UTC, monarch_dodra wrote:
> On Saturday, 18 October 2014 at 23:10:15 UTC, Ola Fosheim 
> Grøstad wrote:
>> In D and (C++ for uint) it is modulo-arithmetic so it is 
>> defined as a circular type with at discontinuity which makes 
>> reasoning about integers harder.
>
> What interesting is that overflow is only defined for unsigned 
> integers. signed integer overflow is *undefined*, and GCC 
> *will* optimize away any conditions that rely on it.

I don't agree with how C/C++ defines arithmetics. I think 
integers should exhibit monotonic behaviour over addition and 
multiplication and that the compiler should assume, prove or 
assert that assigned values are within bounds according to the 
programmer's confidence and specification.

It is the programmers' responsibility to make sure that results 
stays within the type boundaries or to configure the compiler so 
that they will be detected.

If you provide value-ranges for integers then the compiler could 
flag all values that are out of bounds and force the programmer 
to explicitly cast them back to the restricted type.

If you default to 64 bit addition then getting overflows within 
simple expressions is not the most common problem.

> One thing I am certain of, is that making overflow *undefined* 
> is *much* worst than simple having modulo arithmetic. In 
> particular, implementing trivial overflow checks is much easier 
> for the average developper. And worst case scenario, you can 
> still have library defined checked integers.

One big problem with that view is that  "a < a+1" is not an 
overflow check, it is the result of aliasing. It should be 
optimized to true. That is the only sustainable interpretation 
from a correctness point of view.

Even if  "a < a+1" is meant to be an overflow check it completely 
fails if a is a short since it is promoted to int. So this is 
completely stuck in 32-bit land.

In C++ you should default to int and avoid uint unless you do bit 
manipulation according to the C++ designers.

There are three reasons: speed, portability to new hardware and 
correctness.


More information about the Digitalmars-d mailing list