UB in D

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Sat Jul 9 16:17:59 PDT 2016


On 07/09/2016 06:36 PM, Timon Gehr wrote:
> Undefined behaviour means the language semantics don't define a
> successor state for a computation that has not terminated. Do you agree
> with that definition? If not, what /is/ UB in D, and why is it called UB?

Yah, I was joking with Walter that effectively the moment you define 
undefined behavior it's not undefined any longer :o). It happens to the 
best of us. I think we're all aligned here.

There's some interesting interaction here. Consider:

int fun(int x)
{
     int[10] y;
     ...
     return ++y[9 >> x];
}

Now, under the "shift by negative numbers is undefined" rule, the 
compiler is free to eliminate the bounds check from the indexing because 
it's always within bounds for all defined programs. If it isn't, memory 
corruption may ensue. However, if the compiler says "shift by negative 
numbers is implementation-specified", the the compiler cannot portably 
eliminate the bounds check.

It's a nice example illustrating how things that seem to have nothing 
with memory corruption do effect it.


Andrei



More information about the Digitalmars-d mailing list