crash when using &this in struct constructor

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Jul 16 22:21:12 UTC 2018


On Mon, Jul 16, 2018 at 10:08:34PM +0000, Eric via Digitalmars-d-learn wrote:
> This makes the compiler crash. Is it illegal code?
> 
> struct List {
>   private List* head;
>   private List* tail;
> 
>   this(int x) {
>     head = null;
>     tail = &this; // <-- crasher
>   }
> }
> 
> List2 ls = 2;

It's not illegal per se, but a very, very bad idea in general, because
in D, structs are expected to be int-like POD values that can be freely
copied/moved around by the compiler.  More specifically, when structs
are passed into functions or returned from functions, they may be moved
around.  Which means internal pointers will wind up being wrong.

This can be somewhat alleviated with a postblit ctor, but it doesn't
cover all the cases, and the above code looks like one of the cases
where it will likely not cover all cases.  So yeah, you're probably
getting a dangling pointer because of this.

If you need something that doesn't move around, either allocate the
struct on the heap using `new`, or use classes instead.  Note that while
the former will work, it will still require care, because passing the
resulting struct around will pass it by value, and you end up with the
same dangling pointer problem again.  So you really want to be using
classes for this.

Or rethink your algorithms so that they don't depend on having internal
pointers.


T

-- 
Give me some fresh salted fish, please.


More information about the Digitalmars-d-learn mailing list