Disallow null references in safe code?

Marc Schütz" <schuetzm at gmx.net> Marc Schütz" <schuetzm at gmx.net>
Sun Feb 2 01:56:04 PST 2014


On Sunday, 2 February 2014 at 07:54:26 UTC, Jonathan M Davis 
wrote:
> On Saturday, February 01, 2014 19:44:44 Andrei Alexandrescu 
> wrote:
>> On 2/1/14, 7:35 PM, deadalnix wrote:
>> > http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
>> 
>> Whoa, thanks. So the compiler figures null pointer dereference 
>> in C is
>> undefined behavior, which means the entire program could do 
>> whatever if
>> that does happen.
>
> I think that article clearly illustrates that some of Walter's 
> decisions in D
> with regards to fully defining some stuff that C didn't define 
> were indeed
> correct. Undefined behavior is your enemy, and clearly, it gets 
> even worse
> when the optimizer gets involved. *shudder*

Even without undefined behaviour, i.e. a guarantee that 
null-dereference leads to a segfault, the optimizer can deduce 
the pointer to be non-null after the dereference. Otherwise the 
code there could never be reached, because the program would have 
aborted. This in turn can cause the dereference to be optimized 
away, if its result is never used any more (dead store):

auto x = *p;
if(!p) {
     do_something(x);
}

In the first step, the if-block will be removed, because its 
condition is "known" to be false. After that, the value stored 
into x is unused, and the dereference can get removed too.


More information about the Digitalmars-d mailing list