dereferencing null

Jonathan M Davis jmdavisProg at gmx.com
Mon Mar 5 22:26:07 PST 2012


On Tuesday, March 06, 2012 07:16:52 Nathan M. Swan wrote:
> On Friday, 2 March 2012 at 04:53:02 UTC, Jonathan M Davis wrote:
> > It's defined. The operating system protects you. You get a
> > segfault on *nix and
> > an access violation on Windows. Walter's take on it is that
> > there is no point
> > in checking for what the operating system is already checking
> > for - especially
> > when it adds additional overhead. Plenty of folks disagree, but
> > that's the way
> > it is.
> > - Jonathan M Davis
> 
> One thing we must consider is that this violates scope safety.
> 
> This scope(failure) doesn't execute:
> 
> import std.stdio;
> 
> void main() {
>      Object o = null;
>      scope(failure) writeln("error");
>      o.opCmp(new Object());
> }
> 
> That's _very_ inconsistent with the scope(failure) guarantee of
> _always_ executing.

scope(failure) is _not_ guaranteed to always execute on failure. It is _only_ 
guaranteed to run when an Exception is thrown. Any other Throwable - Errors 
included - skip all finally blocks, scope statements, and destructors. That's 
one of the reasons why it's so horrible to try and catch an Error.

If dereferencing null pointers was checked for, it would result in an Error 
just like RangeError, which skips all destructors, finally blocks, and scope 
statements. Such problems are considered unrecoverable. If they occur, your 
program is in an invalid state, and it's better to kill it then to continue. 
If you want to recover from attempting to derefence a null object, then you 
need to check before you dereference it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list