Disallow null references in safe code?

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 1 02:14:35 PST 2014


On Saturday, February 01, 2014 04:01:50 deadalnix wrote:
> > There's nothing unsafe about null pointers/references. @safe is
> > about memory
> > safety, and you can't corrupt memory and otherwise access
> > memory that you're
> > not supposed to with a null pointer or reference.
> > 
> > At some point here, we'll have NonNullable (or NotNull whatever
> > it ends up
> > being called) in Phobos so that folks can have non-nullable
> > references/pointers - e.g. NonNullable!Foo. AFAIK, the only
> > real hold-up is
> > someone completely a fully functional implementation. There's
> > been at least
> > one attempt at it, but as I understand it, there were issues
> > that needed to be
> > worked through before it could be accepted. We'll get there
> > though.
> > 
> > Regardless, we're not adding anything with regards to
> > non-nullable references
> > to the language itself, and there's nothing unsafe about null
> > references.
> > They're just unpleasant to dereference when your code makes
> > that mistake.
> > 
> > - Jonathan M Davis
> 
> Dereferencing it is unsafe unless you put runtime check.

How is it unsafe? It will segfault and kill your program, not corrupt memory. 
It can't even read any memory. It's a bug to dereference a null pointer or 
reference, but it's not unsafe, because it can't access _any_ memory, let 
alone memory that it's not supposed to be accessing, which is precisely what 
@safe is all about.

>  Which is stupid for something that can be verified at compile time.

In the general case, you can only catch it at compile time if you disallow it 
completely, which is unnecessarily restrictive. Sure, some basic cases can be 
caught, but unless the code where the pointer/reference is defined is right 
next to the code where it's dereferenced, there's no way for the compiler to 
have any clue whether it's null or not. And yes, there's certainly code where 
it would make sense to use non-nullable references or pointers, because 
there's no need for them to be nullable, and having them be non-nullable 
avoids any risk of forgetting to initialize them, but that doesn't mean that 
nullable pointers and references aren't useful or that you can catch all 
instances of a null pointer or reference being dereferenced at compile time.

- Jonathan M Davis


More information about the Digitalmars-d mailing list