@safe - why does this compile?

ketmar ketmar at ketmar.no-ip.org
Mon Jul 16 16:36:44 UTC 2018


Johan Engelen wrote:

> On Friday, 13 July 2018 at 14:51:17 UTC, ketmar wrote:
>>
>> yeah. in simple words: safe code is *predictable*, but not 
>> "segfault-less". segfaults (null dereferences) in safe code are allowed, 
>> 'cause they have completely predictable behavior (instant program 
>> termination).
>>
>> @safe doesn't free you from doing your null checks, it protects you from 
>> so-called "undefined behavior" (aka "unpredictable execution results"). 
>> so when we are talking about "memory safety", it doesn't mean that your 
>> code cannot segfault, it means that your code won't corrupt random 
>> memory due to misbehaving.
>
> This is not true when using LDC (and I'd expect the same for GDC).
> With LDC, dereferencing `null` is undefined behavior regardless of 
> whether you are in an @safe context or not.
>
> - Johan

p.s.: it worth noting that *program* *state* is undefined after null 
dereference, though. i.e. program cannot continue execution, and must be 
aborted. in this sense, null dereferencing is defined behavior: it aborts 
the app unconditionally. and if you will catch segfault with some OS 
mechanics, you still cannot reliably do *anything* except immediately 
aborting (strictly speaking, this is true for any `Error` condition, even 
for asserts).

so compiler *can* assume that null dereferencing is something code 
generally won't do, but it cannot do any optimisations assuming that code 
will not dereference nulls at all (dmd -O, afair, was guilty of some such 
optimisations too).

so, code can dereference null, and it will be immediately aborted, without 
any chance to perform cleanup (as program state is undefined after this 
operation). in this sense, null dereferencing is "defined behavior".


More information about the Digitalmars-d-learn mailing list