On Sunday, 24 April 2022 at 21:00:50 UTC, Alain De Vod wrote:
Is this a correct program to explicit call destroy & free ?

```
void main(){
    int[] i=new int[10000];
    import object: destroy;
    destroy(i);
    import core.memory: GC;
    GC.free(GC.addrOf(cast(void *)(i.ptr)));
}
```

A few picks.

1: You do not need to import `destroy`. Everything in `object` is automatically imported.

2: As others have said, destroying an int, or an array if them, is meaningless, since they do not have destructors. The only thing your call does is to set `i` to `null`. In this case it means that there are no more references to the array, so the garbage collector can collect it at some point.

3: Because `i` is now null, `GC.free` also does nothing. If you had something that really mandated using `destroy`, you'd want to use `destroy!false(i)` to avoid setting `i` to `null`.

4: Manually freeing garbage collected memory is just as dangerous as freeing manually managed memory. It's preferable to just let the GC collect the memory. Also like said, there's probably no point to allocate with GC in the first place if you're going to manually free the memory.

5: If you're in a hurry to free the memory, a safer way is to call `GC.collect`. It will most likely free your old data immediately. Don't trust it quite 100% though, since it's possible that some unlucky bit pattern in your remaining data, that isn't really a pointer, "points" to your old data and it won't get collected. Using a precise GC would eliminate that risk I think.

This is rarely a problem though, as long as you either don't do anything mandatory in destructors, or use `destroy` before forgetting the data. The GC can still usually free the majority of your memory.

Reply via email to