Fixing C's Biggest Mistake

Nick Treleaven nick at geany.org
Fri Dec 30 21:46:41 UTC 2022


On Friday, 30 December 2022 at 20:27:43 UTC, Walter Bright wrote:
> Pattern matching inserts an explicit runtime check, rather than 
> using the hardware memory protection to do the check. All you 
> get with pattern matching is (probably) a better error message, 
> and a slower program.

What that buys you is a way to convert a nullable reference to 
non-nullable, without the possibility of an accidental fatal 
error. Non-nullable reference types that *need no checks 
whatsoever*. No chance of accidentally passing a nullable type to 
a function parameter that is non-nullable. No segfault ever 
unless you use the clear red flag `unwrap` escape hatch which is 
obvious in code review.

Plus sometimes whole program optimization can remove those 
checks. The compiler could potentially generate another version 
of a function taking a nullable parameter, one for a non-nullable 
reference. Any null path is statically removed in that version.

> You still get a fatal error, if the pattern match arm for the 
> null pointer is fatal.

If the arm for null is fatal then the programmer must have 
deliberately opted-in to a fatal error by typing e.g. 
`assert(0)`. Not accidentally forgetting to handle null, which is 
a common mistake.

> You can also get a better error message with a seg fault if you 
> code a trap for that error.
>
> Isn't it great that the hardware provides runtime null checking 
> for you at zero cost?
>
> If a seg fault resulted in memory corruption, then I agree with 
> you. But it doesn't, it's at zero cost, your program runs at 
> full speed.

Unfortunately it's not 100% reliable. If you have a null 
reference to a type with fields whose offset is big enough to 
take it into a valid memory address, then that hardware check 
won't catch it. (And anything which is not guaranteed memory-safe 
is not supposed to be allowed in @safe code).


More information about the Digitalmars-d mailing list