Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: null dereference

Tags:

d

This code:

int main(char[][] args)
{
  MyObject obj;
  obj.x;
  return 0;
}

gives me: Error: null dereference in function _Dmain when I compile it with -O flag (on dmd2) Why? Isn't obj allocated on the stack? Should I always use new to create objects?

like image 844
szx Avatar asked Feb 26 '23 17:02

szx


1 Answers

Summary: you have to new objects. Always.

D's classes are closer to C# or Java than C++. Specifically, objects are always, always reference values.

MyObject is, under the hood, a pointer to the actual object. Thus, when you use MyObject obj;, you're creating a null pointer, and have not, in fact, created an object. An object must be created using the new operator:

auto obj = new Object();

This creates obj on the heap.

You cannot directly construct objects on the stack in D. The best you can do is something like this:

scope obj = new MyObject;

The compiler is allowed to place the object on the stack, but doesn't have to.

(Actually, I suspect this might be going away in a future version of D2.)

On a side note, if you are using D2, then I believe your main function should look like this:

int main(string[] args)
{
    ...
}

char[] and string have the same physical layout, but mean slightly different things; specifically, string is just an alias for immutable(char)[], so by using char[] you're circumventing the const system protections.

like image 119
DK. Avatar answered Mar 03 '23 06:03

DK.