www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Should __ArrayDtor be called for uninitialised arrays?

reply Teodor Dutu <teodor.dutu gmail.com> writes:
Hi,

The following code calls `__ArrayDtor` at the end of `main`. 
However, since `arr` is uninitialised, `free(p)` produces a 
segmentation fault.
```d
struct S
{
     int *p;

     ~this()
     {
         free(p);
     }
}

void main()
{
     S[3] arr = void;
}
```

Is this the expected behaviour? One possible fix is to let the 
programmer handle the destruction of void-initialised arrays 
themselves.

I am asking because, in 
[`_d_arrayctor`](https://github.com/dlang/druntime/blob/0254b3f3dd263fbf7496354c6fcb53026fa44098/src/core/internal/array/
onstruction.d#L73), the `throw` introduces call to `__ArrayDtor`, which
destroys the array `to`. This call is unnecessary, as the `_d_arrayctor`
already destroys the initialised elements of `to`, while the uninitialised ones
need not be destroyed, as I said above.

Thanks,
Teodor
Nov 18 2021
parent reply Adam D Ruppe <destructionator gmail.com> writes:
On Thursday, 18 November 2021 at 12:27:54 UTC, Teodor Dutu wrote:
 Is this the expected behaviour?
Yes, this is specified. https://dlang.org/spec/struct.html#struct-destructor It is always called when it goes out of scope. You're supposed to ensure S.init's destructor is a harmless no-op because it is always called. But if you void initialize of course it isn't S.init, it is S.random. But the spec does give you a way to handle destruction yourself: use a union. See more: http://dpldocs.info/this-week-in-d/Blog.Posted_2021_03_15.html#tip-of-the-week
Nov 18 2021
parent Teodor Dutu <teodor.dutu gmail.com> writes:
On Thursday, 18 November 2021 at 13:32:32 UTC, Adam D Ruppe wrote:
 But the spec does give you a way to handle destruction 
 yourself: use a union. See more: 
 http://dpldocs.info/this-week-in-d/Blog.Posted_2021_03_15.html#tip-of-the-week
This worked. Thanks!
Nov 18 2021