Why would an initialised struct pointer field be null in the struct's destructor?

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 20 05:25:39 PDT 2017


On Saturday, 20 May 2017 at 10:48:54 UTC, Gary Willoughby wrote:
> In the following code, the `_foo` pointer (of the Foo struct) 
> is null in the first call to the destructor. Why is this? I 
> think it's got something to do with the foreach loop but I'm 
> not sure. Any ideas?

Oof. Dangerous stuff. As Moritz pointed out, default opAssign 
will call the destructor on Foo. I should, however, elaborate 
further. You're dealing with uninitialized data. calloc() gives 
you zero-initialized block, which is not necessarily how Foo.init 
would look (it does in this case, but that's not true in general 
case).
malloc() gives you a potentially garbage-filled block, which is 
even more dangerous.

When filling an array of uninitialized values, use 
std.algorithm.moveEmplace(src, dst) instead of assignment. And, 
if you have destructors, you have to call the destructors 
manually when you free the array.
Furthermore, since Bar._data is an array of Foos, and Foo has a 
pointer in it, you might want to register the Bar._data array 
with the GC (GC.addRange, GC.removeRange). Unless you're willing 
to manually make sure that GC *never* sees those pointers.


More information about the Digitalmars-d-learn mailing list