dereferencing null

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 2 17:26:09 PST 2012


On Friday, March 02, 2012 16:19:13 deadalnix wrote:
> Le 02/03/2012 15:37, Jacob Carlborg a écrit :
> > On 2012-03-02 14:00, deadalnix wrote:
> >> Le 02/03/2012 05:51, Jonathan M Davis a écrit :
> >>> 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.
> >> 
> >> The assertion that it has overhead isn't true.You'll find solutions
> >> without overhead (using libsigsegv in druntime for example).
> >> 
> >> BTW, object should be non nullable by default, if you ask me. The
> >> drawback of null is way bigger than any benefit.
> > 
> > Isn't it quite unsafe to throw an exception in a signal ?
> 
> The signal handler is called on top of the stack, but the information to
> retrieve the stack trace are system dependant. BTW, using lib like
> libsigsegv can help a lot to make it safe. It isn't safe ATM, but it is
> doable.

You could definitely set it up to print a stack trace in the signal handler on 
at least some systems, but throwing an exception would _not_ be a good idea. 
So, a NullPointerException _would_ require additional overhead, because it 
would require checking the pointer/reference for null every time that you 
dereference it.

Of course, it wouldn't work if anyone installed their own signal handler, so 
using a signal handler has its limits anyway, but it could be done.

- Jonathan M Davis


More information about the Digitalmars-d mailing list