Error: Zero Dereferencing

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 the -O flag (by dmd2). Why? Isn't obj allocated on the stack? Should I always use new to create objects?

+4
source share
2 answers

Summary : you have new objects. Is always.

D classes are closer to C # or Java than C ++. In particular, objects are always, always referential values.

MyObject is under the hood, a pointer to the actual object. That way when you use MyObject obj; , you are creating a null pointer and have not actually created an object. The object must be created using the new operator:

 auto obj = new Object(); 

This creates obj on the heap.

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

 scope obj = new MyObject; 

The compiler is allowed to push the object onto the stack, but is not necessary.

(In fact, I suspect this might go away in a future version of D2.)

On the side of the note, if you are using D2, I suggest that your main function should look like this:

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

char[] and string have the same physical layout, but mean slightly different things; in particular, string is just an alias for immutable(char)[] , so by using char[] you bypass the const system protection.

+8
source

I don't read your code very well since I'm a VB guy, but it looks like you are initiating an object without its value.

You create an object called obj. You call obj.x then you return "0" (zero)

what exactly are you doing? I am sure obj should be NEW and you need to return something other than physical "0"

0
source

Source: https://habr.com/ru/post/1314913/


All Articles