null dereference exception vs. segfault?

Jonathan M Davis jmdavisprog at gmail.com
Mon Aug 2 01:56:15 PDT 2010


On Sunday 01 August 2010 21:59:42 Ryan W Sims wrote:
> The following code fails with a "Bus error" (OSX speak for "Segfault,"
> if I understand correctly).
> 
> // types.d
> import std.stdio;
> 
> class A {
>      int x = 42;
> }
> 
> void fail_sometimes(int n) {
>      A a;
>      if (n == 0) {
>          a = new A;  // clearly a contrived example
>      }
>      assert(a.x == 42, "Wrong x value");
> }
> 
> void main() {
>      fail_sometimes(1);
> }
> 
> It's even worse if I do a 'dmd -run types.d', it just fails without even
> the minimalistic "Bus error." Is this correct behavior? I searched the
> archives & looked at the FAQ & found workarounds (registering a signal
> handler), but not a justification, and the threads were from a couple
> years ago. Wondering if maybe something has changed and there's a
> problem with my system?
> 
> --
> rwsims

You are getting a segmentation fault because you are dereferencing a null 
reference. All references are default initialized to null. So, if you fail to 
explicitly initialize them or to assign to them, then they stay null, and in 
such a case, you will get a segfault if you try to dereference them.

If you changed your code to

import std.stdio;

class A {
     int x = 42;
}

void fail_sometimes(int n) {
     A a;
     if (n == 0) {
         a = new A;  // clearly a contrived example
     }
     assert(a !is null, "a shouldn't be null");
     assert(a.x == 42, "Wrong x value");
}

void main() {
     fail_sometimes(1);
}


you would get output something like this

core.exception.AssertError at types.d(12): a shouldn't be null
----------------
./types() [0x804b888]
./types() [0x8049360]
./types() [0x8049399]
./types() [0x804ba54]
./types() [0x804b9b9]
./types() [0x804ba91]
./types() [0x804b9b9]
./types() [0x804b968]
/opt/lib32/lib/libc.so.6(__libc_start_main+0xe6) [0xf760bc76]
./types() [0x8049261]


Unlike Java, there is no such thing as a NullPointerException in D. You just get 
segfaults - just like you would in C++. So, if you don't want segfaults from 
derefencing null references, you need to make sure that they aren't null when 
you dereference them.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list