Freeing memory from C
John Colvin
john.loughran.colvin at gmail.com
Tue Dec 3 04:31:15 PST 2013
On Tuesday, 3 December 2013 at 10:57:51 UTC, Chris wrote:
> I have a C module that dynamically allocates memory for a
> string like so:
>
> char *result = (char*)malloc(length + 1); // 'length' has been
> calculated
>
> When I call it from D (via extern (C)), is it ok to free it
> from there like so:
>
> void callFunction() {
> auto result = callToCFunction(); // Returns above *result
> // ...
> std.c.stdlib.free(result);
> }
>
> The problem is that, as it is now, *result is allocated in a
> different place in the C module (not in "callToCFunction()) and
> cannot be freed before D has called it.
>
> If D cannot free it in this way, I'll have a serious memory
> leak and I'll have to rewrite the existing C module (which is
> probably better given the awkward situation above).
You should be fine to free in that way as long as you haven't
done anything crazy like separately static linking libc.
core.stdc.stdlib; is the correct module to use, std.c.* only
exist for backwards compatibility.
More information about the Digitalmars-d-learn
mailing list