null dereference exception vs. segfault?
Jonathan M Davis
jmdavisprog at gmail.com
Mon Aug 2 01:49:40 PDT 2010
On Monday 02 August 2010 00:05:40 Jeffrey Yasskin wrote:
> 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.
_All_ variables in D are initialized with a default value. There should be _no_
undefined behavior with regards to initializations. D is very concientious about
avoiding undefined behavior. In the case of references and pointers, they are
initialized to null. There's not really such a thing as using a variable without
initializing it, because variables are default initialized if you don't
initialize them yourself. The _one_ exception would be if you explicitly
initialized a variable to void:
int[] a = void;
In that case, you are _explicitly_ telling the compiler not to default
initialize the variable. That _can_ lead to undefined behavior and is definitely
unsafe. As such, it is intended solely for the purposes of optimizing code where
absolutely necessary. So, you really shouldn't have any variables in your code
that weren't initialized, even if you didn't initialize them explicitly.
The pages that you're looking at there need to be updated for clarity.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list