safety: null checks

Johan Engelen j at j.nl
Mon Nov 23 12:01:08 UTC 2020


On Sunday, 22 November 2020 at 23:00:25 UTC, Ola Fosheim Grostad 
wrote:
> On Sunday, 22 November 2020 at 22:36:40 UTC, Paul Backus wrote:
>> Memory safety is concerned specifically with avoiding 
>> undefined behavior. Crashing the program isn't undefined 
>> behavior, so it's allowed in @safe code.
>
> I understand what you mean, but at high optimization levels 
> dereferencing a null pointer can trigger undefined behaviour.

I'll reiterate what I've been saying many times already: in LDC, 
null dereference in Undefined Behavior. What follows is that code 
should _actively_ check for null to be safe. Checking for null is 
not included by the compiler in @safe code.

- Note that accessing memory location 0x0 will probably crash 
your program on most systems, but definitely not all. For example 
with WebAssembly, 0 is a validly accessibly memory location.
- "Dereferencing a null pointer" in D language context does _not_ 
mean accessing memory address 0 on system level.
-- Calling a class method a.foo() when a==null is technically 
dereferencing `a`, even if the `foo` call is devirtualized, does 
not access any member variables, etc.
-- Accessing struct member that is not at offset 0 will also lead 
to accesses to other locations than 0.


-Johan



More information about the Digitalmars-d mailing list