[RFC] Throwing an exception with null pointers

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Wed Apr 16 16:27:08 UTC 2025


On 16/04/2025 11:38 PM, Derek Fawcus wrote:
> On Wednesday, 16 April 2025 at 08:49:39 UTC, Richard (Rikki) Andrew 
> Cattermole wrote:
>>> How is out of bounds access related to null pointers throwing 
>>> exceptions?
>>
>> Out of bounds on a slice uses a read barrier to throw an exception.
>>
>> A read barrier to prevent dereferencing a null pointer is exactly the 
>> same concept.
>>
>> One is 0 or 1.
>>
>> Second is 0 or N.
> 
> Exactly what are you referring to by "read barrier"?
> 
> To me it has a specific technical meaning, related to memory access and 
> if/when one access may pass another.  It has nothing to do with 
> exceptions, but rather the details of how a CPU architecture approaches 
> superscalar memory accesses (reads and/or writes), and how they are (or 
> may be) re-ordered.
> 
> However I would not classify the bounds check performed as part of 
> accessing a slice as a "read barrier", rather it is a manual range check.
> 
> So by "read barrier" for null's do you simply mean having the compile 
> generate a "compare to zero" instruction, followed by a "jump if zero" 
> to some error path?

Yes.

It would then call a compiler hook just like array bounds checks do.

> If so, then while it may catch errors (and I have no objection to 
> optionally generating such null checks); it is not IMO a means of error 
> recovery - simply another means of forcing a crash.

This is why I think its important that we make this configurable via a 
global function pointer. Like we do for asserts.

It allows people to configure what it does rather than pick for them.



More information about the Digitalmars-d mailing list