Struct delegate access corruption

Steven Schveighoffer schveiguy at gmail.com
Wed Feb 17 15:48:17 UTC 2021


On 2/17/21 10:38 AM, z 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.
> 
> i've isolated the problem by adding writefln calls before calling the 
> delegate and inside the delegate(the functions are defined in the struct 
> as member functions, the delegate itself is set in the constructor) :
> 
> In the code that uses the delegate :
>> writefln!"test %s"(a, &a);
>> T b = a.d();//the delegate
> While in the most used delegate :
>> writefln!"test2 %s %s"(this, &this);
> The contents and pointers don't match(they're random, full of 0, -nan, 
> -inf and other invalid values), are they(delegates) supposed to be used 
> like this?

With structs and delegates, you have to be careful because structs are 
copied easily, and using a delegate on a struct that is no longer in 
scope is going to lead to memory corruption.

In order to properly ensure delegates are pointing to valid data, make 
sure the struct is still not moved or overwritten, or it is allocated on 
the heap.

-Steve


More information about the Digitalmars-d-learn mailing list