C `restrict` keyword in D

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 6 13:22:53 PDT 2017


On Wednesday, September 06, 2017 19:40:16 Johan Engelen via Digitalmars-d 
wrote:
> On Tuesday, 5 September 2017 at 22:59:12 UTC, Jonathan M Davis
>
> wrote:
> > dmd and the spec were written with the assumption that the CPU
> > is going to segfault your program when you dereference a null
> > pointer. In the vast majority of cases, that assumption holds.
>
> In my terminology, "dereference" is a language spec term. It is
> not directly related to what the CPU is doing.
> ```
> struct S {
>    void nothing() {}
> }
>
> void foo (S* s) {
>    (*s).nothing(); //dereference must crash on null?
> }
> ```
> If you call the `(*s)` a dereference, then you are agreeing with
> "my" dereference terminology. ( used the * for extra clarity;
> "s.nothing()" is the same.)
>
> In LDC, dereferencing a null ptr is UB.
> DMD is assuming the same, or something similar. Otherwise DMD
> wouldn't be able to optimize foo in this example to an empty body
> as it does currently.
> (go go null-checks everywhere)

I would argue that if the dereferencing of the pointer is optimized out,
then it is never dereferenced, and therefore, it doesn't need to crash. It's
only if it's actually dereferenced that the crashing needs to occur, because
that's what's need for @safe to be @safe. I can totally believe that the
spec needs to be clearer about this, but I would definitely interpret it to
mean that if the pointer is actually dereferenced, the program must crash
and not that your code example must crash even if it's optimized. And I
would be surprised if Walter meant anything else. He just isn't always good
about writing the spec in a way that others agree that it means what he
meant, and to be fair, it can be very hard to write things in an unambiguous
way. Regardless, I don't see a problem here - or a need to insert a bunch of
null checks. The spec should probably be clarified, but the only thing that
I'm aware of that I would consider a hole in dereferencing null right now is
the fact that it relies on the CPU to segfault the program in cases where
the object is too large for that to occur - and in those cases, null checks
really should be inserted. For objects that are small enough to trigger
segfaults with null, null checks should not be necessary.

- Jonathan M Davis



More information about the Digitalmars-d mailing list