Reputation: 1778
I'm using Native Abstractions for Node.js (NAN) to call C++ functions from a node.js program.
One C++ allocates a buffer using new char[] and returns it to my node.js program.
My question is that I do not know who is responsible for freeing this memory. I'm using NanReturnValue in my C++ code to return a pointer to the buffer. If I delete[] it right after, the node.js code just gets garbage. But if I don't delete[] it at all, it appears there may be a memory leak (although its possible the leak is elsewhere). The documentation is very sparse and it isn't clear who (whether javascript or C++) is responsible for deallocating this memory.
Upvotes: 1
Views: 594
Reputation: 574
You need to hook into the GC in v8 to get a callback to your C++ code letting you know that no JavaScript object has a reference to the buffer you returned.
In that C++ callback, you can delete
the ArrayBuffer memory.
I'm sure you've seen these docs, but pay attention to the Nan::FreeCallBack() section: https://github.com/nodejs/nan/blob/master/doc/buffers.md#api_nan_free_callback
Here is a quick example:
//defined before hand:
static void FreeCallback(char* data, void* message) {
free(message);
}
//some where in a function:
Local<Object> buf_obj = NanNewBufferHandle((char*)zmq_msg_data(message), zmq_msg_size(message), FreeCallback, message);
For your buffer, there might be some differences, but I hope that gives you an idea of the direction to go.
Upvotes: 1