dereferencing null

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 1 20:51:36 PST 2012


On Friday, March 02, 2012 05:37:46 Nathan M. Swan wrote:
> Am I correct that trying to use an Object null results in
> undefined behavior?
> 
>      Object o = null;
>      o.opCmp(new Object); // segmentation fault on my OSX machine
> 
> This seems a bit non-D-ish to me, as other bugs like this throw
> Errors (e.g. RangeError).
> 
> It would be nice if it would throw a NullPointerError or
> something like that, because I spent a long time trying to find a
> bug that crashed the program before writeln-debugging statements
> could be flushed.

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.

If you really care about checking for it, then just assert:

assert(obj !is null);

or

assert(obj);

(the second one will also call the object's invariant).

- Jonathan M Davis


More information about the Digitalmars-d mailing list