null dereference exception vs. segfault?

Mafi mafi at example.org
Mon Aug 2 10:24:49 PDT 2010


Am 02.08.2010 16:50, schrieb Ryan W Sims:
> On 8/2/10 1:56 AM, Jonathan M Davis wrote:
>> 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.
>
> Yes, I know *why* I'm getting a segfault, thank you - I set up the
> example explicitly to defeat the compiler's null checking to test the
> behavior. I was startled that there wasn't an exception thrown w/ a
> stack trace.
>
> [snip]
>
>>
>>
>> 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
>
> That was my question, thanks. It seemed like such an un-D thing to have
> happen; I was surprised. I guess w/o the backing of a full virtual
> machine, it's tricker to catch null dereferences on the fly, but boy
> it'd be nice to have. Don't want to re-fire the debate here, though.
>
> --
> rwsims

If you want a NullPointerException as part of your program flow, you can 
use enforce() (in std.contracts I think). I don't think catching a 
NullPointerException in a big code block where you don't know which 
dereferencing should fail is good style.

Mafi


More information about the Digitalmars-d-learn mailing list