Freeing memory from C

Chris wendlec at tcd.ie
Tue Dec 3 02:57:50 PST 2013


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).




More information about the Digitalmars-d-learn mailing list