Issue with clearing memory

This may be the wrong place for this, but I have a feeling it all boils down to a c++ issue.

https://github.com/CraigglesO/webp-js/blob/master/src/webp_js.cc#L43

I use a c++ wrapper to connect with NodeJS. I use the webp library to read in data (for this example).

1
2
3
4
5
6
  // make a copy and cleanup
    uint8_t* cpy;
    cpy = new uint8_t[length];
    memcpy(cpy, webpData, length);
    obj.Set(Napi::String::New(env, "buffer"), Napi::ArrayBuffer::New(env, cpy, length));
    WebPFree(webpData);


Here is where the magic happens. I make a copy and cleanup webpData, but the NodeJS engine is never aware to garbage collect because of a mistake I think I am making here. So after running my script on 10s of thousands of images, the ram is eaten alive pretty quickly.

Any thoughts from the C++ side of things?

Thanks.
Where is the memory allocated to cpy freed?
I thought because it was wrapped in the v8 engine, it was aware of the memory and garbage collected on its own.

edit - the wrapper claims that it takes ownership and cleans itself:
https://github.com/nodejs/node-addon-api/blob/main/doc/array_buffer.md

edit edit -

It looks like I had it wrong? It says it does not assume ownership, but the finalizer (callback) is where I should free it?
1
2
3
4
static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env,
                       void* externalData,
                       size_t byteLength,
                       Finalizer finalizeCallback);
Last edited on
Actually:
The Napi::ArrayBuffer instance does not assume ownership for the data and expects it to be valid for the lifetime of the instance. The data can only be freed once the finalizeCallback is invoked to indicate that the Napi::ArrayBuffer has been released.
Edit, yeah guys sorry. I misinterpreted the wrapper.

The final result was:
1
2
3
obj.Set(Napi::String::New(env, "buffer"), Napi::ArrayBuffer::New(env, cpy, length, [](Env /*env*/, void* finalizeData) {
      delete[] static_cast<uint8_t*>(finalizeData);
    }));


And that fixed it. I thought the ArrayBuffer had to take in a uint8_t so it would just release it automatically. but that is not the case.

Thanks for the help everyone :)
Last edited on
Topic archived. No new replies allowed.