Memory leak issue between extern (c) and D function

Paul Backus snarwin at gmail.com
Fri Apr 14 04:43:39 UTC 2023


On Friday, 14 April 2023 at 03:50:37 UTC, backtrack wrote:
> Dear All, I am new to D lang. I have been given a task to 
> consume the .dll generated from a D lang project.
>
> I added extern (c) function for call the .dll from CPP file. i 
> have code like below
>
>
> ```
> // myfile.d
> extern(c)
> {
>
>     mystruct* getmystruct()
>     {
>         mystruct* mystruct =  
> cast(mystruct*)malloc(mystruct.sizeof);
>         return mystruct;
>
>     }
> ```
[...]
> Now i have my cpp file which calls like below
>
> ```
> mystruct* mystruct = lib.getmystruct();
> char* output = lib.do_some_work(mystruct, "input", 5);
>
> ```
>
> The problem i am facing is, the memory keep on increasing and i 
> am not able to fix the memory issue. I am suspecting that since 
> the D lang function is called from extern(c) function GC is not 
> clearing the memeory.

The GC does not clean up memory allocated by `malloc`. Since 
you're using `malloc` to allocate your memory, the only way you 
can free it is by using `free`.

If you want the GC to clean up your memory, use `new` to allocate 
it instead of `malloc`. Like this:

```d
mystruct* getmystruct()
{
     return new mystruct;
}
```


More information about the Digitalmars-d-learn mailing list