Hi all, I'm porting the cmark markdown implementation to Node.js using Emscripten, and this is what I found.
There's a C function returning a char* string. The C function states in its docs that the caller should free the return value.
But in ccall, specifically in this line, we're discarding the pointer to the return value without calling _free. This leads to a memory leak, I have tested it.
When I replace this line with something more elaborate, like this:
if (returnType === 'string') {
let foo = Pointer_stringify(ret)
_free(ret)
ret = foo
}
Everything is great again. (But I assume this patch can break someone else's C function.)
What do?
In such a case, you need to call free yourself after doing ccall. Something like this:
var ptr = ccall('foo');
// use ptr
Module._free(ptr);
That basically does what a C program would do for that API: call it, then free it.
@kripken Hi! Yep, thanks for the tip. The thing is, ccall() doesn't return the pointer, instead it converts it to a string and throws away. So I ended up patching the function.
Oh, now I understand. Yeah, since ccall converts it, the caller can't free...
We should probably add an optional parameter to ccall, or something like that. Reopening.
@kripken
If the caller wants to the memory to be released, they can specify number instead of string as the return type, convert the returned pointer to a string manually with pointer_stringify(), and then free() it. Is the optional parameter to do that automatically really needed?
@asnasnasn yeah, good point, with some extra work this is already possible. Probably not worth a new option, then, I agree.
This issue has been automatically marked as stale because there has been no activity in the past year. It will be closed automatically if no further activity occurs in the next 7 days. Feel free to re-open at any time if this issue is still relevant.
Most helpful comment
In such a case, you need to call free yourself after doing ccall. Something like this:
That basically does what a C program would do for that API: call it, then free it.