Skip to content

Is node-addon-api@1.2.0 leaking memory? #237

Description

@fivdi

If the following addon:

my-object.h

#include<napi.h>classMyObject : publicNapi::ObjectWrap<MyObject> {
public:static Napi::Object Init(Napi::Env env, Napi::Object exports);
MyObject(const Napi::CallbackInfo& info);
private:static Napi::FunctionReference constructor;
voidOpen(const Napi::CallbackInfo& info);
};

my-object.cc

#include"my-object.h"classOpenAsyncWorker : publicNapi::AsyncWorker {
public:OpenAsyncWorker(Napi::Function& callback)
: Napi::AsyncWorker(callback) {
}
voidExecute() {
}
};
Napi::FunctionReference MyObject::constructor;
Napi::Object MyObject::Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(env, "MyObject", {
InstanceMethod("open", &MyObject::Open)
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("MyObject", func);
return exports;
}
MyObject::MyObject(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<MyObject>(info) {
}
voidMyObject::Open(const Napi::CallbackInfo& info) {
Napi::Function cb = info[0].As<Napi::Function>();
OpenAsyncWorker* worker = newOpenAsyncWorker(cb);
worker->Queue();
}

addon.cc

#include<napi.h>
#include"my-object.h"
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
returnMyObject::Init(env, exports);
}
NODE_API_MODULE(addon, InitAll)

is tested with the following JavaScript:

'use strict';constaddon=require('bindings')('addon.node');constmyObject=newaddon.MyObject();letcount=0;functionopen(){myObject.open(()=>{count+=1;if(count%1000000===0){console.log(count);}open();});}open();

then the memory usage of the node process keeps increasing and increasing and the process ends up crashing after the async open method has been called about 18 million times.

Here's the output of the program:

pi@raspberrypi:~/node-addon-api-leak $ node test/leak.js (node:1304) Warning: N-API is an experimental feature and could change at any time.
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000
9000000
10000000
11000000
12000000
13000000
14000000
15000000
16000000
17000000
18000000
Killed

The complete addon can be seen here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions