Skip to content

Is [email protected] leaking memory? #237

Closed
@fivdi

Description

@fivdi

If the following addon:

my-object.h

#include <napi.h>

class MyObject : public Napi::ObjectWrap<MyObject> {
 public:
  static Napi::Object Init(Napi::Env env, Napi::Object exports);
  MyObject(const Napi::CallbackInfo& info);

 private:
  static Napi::FunctionReference constructor;

  void Open(const Napi::CallbackInfo& info);
};

my-object.cc

#include "my-object.h"

class OpenAsyncWorker : public Napi::AsyncWorker {
  public:
    OpenAsyncWorker(Napi::Function& callback)
      : Napi::AsyncWorker(callback) {
    }

    void Execute() {
    }
};

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) {
}

void MyObject::Open(const Napi::CallbackInfo& info) {
  Napi::Function cb = info[0].As<Napi::Function>();
  OpenAsyncWorker* worker = new OpenAsyncWorker(cb);
  worker->Queue();
}

addon.cc

#include <napi.h>
#include "my-object.h"

Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
  return MyObject::Init(env, exports);
}

NODE_API_MODULE(addon, InitAll)

is tested with the following JavaScript:

'use strict';

const addon = require('bindings')('addon.node');
const myObject = new addon.MyObject();
let count = 0;

function open() {
  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