Struct delegate access corruption

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Feb 17 17:45:01 UTC 2021


On Wed, Feb 17, 2021 at 03:38:00PM +0000, z via Digitalmars-d-learn wrote:
> So i've upgraded one of my structs to use the more flexible delegates
> instead of function pointers but when the member function tries to
> access the struct's members, the contents are random and the program
> fails.

You're likely running into the struct self-reference problem.  Keep in
mind that in D, structs are what Andrei calls "glorified ints", i.e.,
they are value types that get freely copied around and passed around in
registers.  Meaning that the address of a struct is likely to change
(and change a lot as it gets passed around), unless you explicitly
allocated it on the heap.  So if you have any pointers to the struct
(including implicit pointers like delegate context pointers) stored
inside itself, they are highly likely to become dangling pointers as the
struct gets copied to another place and the old copy goes out of scope.

I.e., the following is NOT a good idea:

	struct S {
		void delegate() member;
		this() {
			member = &this.impl;
		}
		private void impl();
	}

because a pointer to S is stored inside S itself, so as soon as S gets
copied or moved, the delegate context pointer is no longer valid (or
else points to a different copy of the struct than the one it will be
called from).

If you need to store references to an aggregate inside itself, you
should be using a class instead.  Or be absolutely sure you allocate the
struct on the heap with `new`, AND never pass it around except by
reference (using pointers).


T

-- 
Almost all proofs have bugs, but almost all theorems are true. -- Paul Pedersen


More information about the Digitalmars-d-learn mailing list