[OT] OT: Null checks.

Timon Gehr timon.gehr at gmx.ch
Sat May 3 22:10:17 UTC 2025


On 5/3/25 21:01, Walter Bright wrote:
> A null check should only be done when converting a nullable pointer to a 
> non-nullable one. Doing a runtime null check before doing a dereference 
> check is redundant, because the CPU will do it for you.

No, it will not. It's UB in modern compiler backends, and there are 
increasingly important targets such as WASM where you can just write 
through a null pointer without any page protection. It also does not 
work in real mode, as well as some bare-metal/embedded systems.

Furthermore, there are no null checks when you pass a dereferenced null 
pointer to a `ref` parameter.

In practice (outside your small DMC compiler backend box), you can only 
dereference a non-null pointer, so dereferencing a nullable pointer is 
actually explicitly one of the cases where you convert it to a 
non-nullable one...

Also, a segfault on some user's machine is a lot less useful than even a 
stack trace, and being able to collect some crash info in a 
`scope(failure)` or similar is even more useful. It can reduce a 
month-long heisenbug hunt into a 15 minute fix.

`assert(0)` in druntime is a similarly frustrating experience.

If there were a flag to enable null checks on any nullable pointer 
dereference, I would enable it immediately in all my projects.


More information about the Digitalmars-d mailing list