How to free memory ater use of "new" to allocate it.
Steven Schveighoffer
schveiguy at gmail.com
Mon Jul 17 13:51:53 UTC 2023
On 7/16/23 11:58 PM, Alain De Vos wrote:
> Maybe code above works when you enforce an Garbage-collection-run ?
>
> Code below works fine. So you cannot use "new" but must use malloc?
>
> ```
>
> import std.stdio:writefln;
> import object: destroy;
> import core.memory: GC;
> import core.stdc.stdlib: malloc,free;
>
>
> void dofun(){
> auto pa=cast(int *)malloc(1000*int.sizeof);
> writefln("%12x",pa);
> auto a=pa[0..1000];
> free(a.ptr);
> }
>
> int main(){
> dofun();
> auto pb=cast(int *)malloc(1000*int.sizeof);
> writefln("%12x",pb);
> auto b=pb[0..1000];
> free(b.ptr);
> return 0;
>
> }
>
> ```
Notice how you didn't call `destroy(a)` there. If you did, then
`free(a)` would be equivalent to `free(null)`, which would do nothing.
-Steve
More information about the Digitalmars-d-learn
mailing list