null dereference exception vs. segfault?

Jeffrey Yasskin jyasskin at gmail.com
Mon Aug 2 00:05:40 PDT 2010


Even better, you can annotate fail_sometimes with @safe, and it'll
still access out-of-bounds memory.

Take the following with a grain of salt since I'm really new to the language.

gdb says:
Reason: KERN_PROTECTION_FAILURE at address: 0x00000008
0x00001e52 in D4test14fail_sometimesFiZv ()

which indicates that 'a' is getting initialized to null (possibly by
process startup 0ing out the stack), and then x is being read out of
it. You can get exactly the same crashes in C++ by reading member
variables out of null pointers. The D compiler is supposed to catch
the uninitialized variable ("It is an error to use a local variable
without first assigning it a value." in
http://www.digitalmars.com/d/2.0/function.html), but clearly it's
missing this one.

I haven't actually found where in the language spec it says that class
variables are pointers, or what their default values are. I'd expect
to find this in http://www.digitalmars.com/d/2.0/type.html, but no
luck.

Looking through the bug tracker ... Walter's response to
http://d.puremagic.com/issues/show_bug.cgi?id=671 seems to indicate
that he isn't serious about uninitialized use being an error. It's
just undefined behavior like in C++.

In any case, the fix for your problem will be to initialize 'a' before using it.

On Sun, Aug 1, 2010 at 9:59 PM, Ryan W Sims <rwsims at gmail.com> 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
>


More information about the Digitalmars-d-learn mailing list