How to free memory ater use of "new" to allocate it.
    Steven Schveighoffer 
    schveiguy at gmail.com
       
    Sun Jul 16 20:51:55 UTC 2023
    
    
  
On 7/16/23 2:41 PM, Alain De Vos wrote:
> Is this ok ?
> ```
> void main(){
>      int[] i=new int[10000];
>      import object: destroy;
>      destroy(i);
>      import core.memory: GC;
>      GC.free(GC.addrOf(cast(void *)(i.ptr)));
> }
> ```
No, that won't work. Check out `i` value after you call `destroy` on it:
```d
destroy(i); // basically sets i = null
assert(i.ptr is null); // yep
GC.free(i.ptr); // basically free(null) which is a no-op
```
Also note that `destroy` is *shallow*. It does not dig into pointers or 
arrays. So even if your array was of elements with a destructor, 
destroying the array doesn't destroy the elements.
In this case, all you need to do is:
```d
GC.free(GC.addrOf(i.ptr));
```
You don't need the cast here. You shouldn't need the addrOf, but this is 
still open: https://issues.dlang.org/show_bug.cgi?id=13558
-Steve
    
    
More information about the Digitalmars-d-learn
mailing list