How does D handle null pointers?

Jonathan M Davis jmdavisprog at gmail.com
Fri Aug 20 15:37:15 PDT 2010


On Friday, August 20, 2010 14:03:59 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

Walter has refused to put in null checks on the theory that the OS does it for 
you - hence the segfault. Of course, then the only way to get a stacktrace is to 
either have a segfault handler which prints one or to look at a core dump 
(assuming that you get one). Neither is a very pleasant solution. There are 
quite a few people who want Walter to put in null checks in at least debug mode, 
but he's against it and no one has been able to convince him. So, as far as null 
goes, you're in essentially the same boat as you're in in C and C++, which is a 
major step back in comparison to C# or Java, much as a lot of the rest of D is a 
step forward.

- Jonathan M Davis


More information about the Digitalmars-d mailing list