How does D handle null pointers?

Rory Mcguire rjmcguire at gm_no_ail.com
Sun Aug 22 03:25:48 PDT 2010


Adam B wrote:

> Hello all,
> 
> Yesterday I started playing with D for the first time, (I'm a Java &
> C++ programmer by day and a python programmer by night).  In my first
> experiments I wanted to prove that:
> 
> 1) Exceptions have stack traces (so you can tell *where* the error
> occurred!) 2) Indexing into an array causes an exception instead of a
> segfault or memory corruption
> 3) Dereferencing null pointers causes an exception instead of a segfault
> 
> D 2.0 seems to handle my first two tests just fine but this program
> causes a segfault:
> 
> ------------
> class A
> {
>     int i;
> }
> 
> int main(char[][] args)
> {
>     A a = null;
>     a.i++;
>     return 0;
> }
> ------------
> 
> I realize that checking every pointer dereference is expensive but, in
> my experience, null pointer dereferences are one of the top 5 runtime
> errors.  At work I troubleshoot java NullPointerExceptions on a weekly
> basis.  Can you imagine trying to troubleshoot a massive web
> application that crashes with the phrase "Segmentation Fault" after
> running just fine for two weeks?  Without a stack trace it's not
> reasonable.
> 
> Does D address this problem?  Perhaps another compiler switch similar
> to the existing -noboundscheck ?
> 
> Cheers
> - Adam B

The only way I currently have checking for nullpointer accesses for classes 
is by using a auto implement of the specific class with a invariant that
asserts.
But it doesn't protect against a latter assign of null. Perhaps overriding
opAssign in the auto implemented class would protect against that.

If that is the case then you would have to initialize instances using 
something like:

A a = nonnull!A;




More information about the Digitalmars-d mailing list