Freeing memory from C
Chris
wendlec at tcd.ie
Tue Dec 3 04:37:22 PST 2013
On Tuesday, 3 December 2013 at 12:31:16 UTC, John Colvin wrote:
> 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.
Ok. Thanks for the answer. std.c.stdlib.free() is mentioned on
the "How to interface to C" page
(http://dlang.org/interfaceToC.html). So maybe that needs an
update.
More information about the Digitalmars-d-learn
mailing list