c++node.jsnode.js-nan

My data disappears when passing buffer to NodeJS from C++


I Have the following situation that I don't understand. I have an app where from NodeJS I'm calling a C++ function using Nan. The code on the C++ side is as follows:

#include <nan.h>
#include <iostream>

using namespace std;
using namespace Nan;
using namespace v8;

//
//  The function that we are going to call from NodeJS
//
NAN_METHOD(Combine)
{
    char str[80];

    strcpy (str,"these ");
    strcat (str,"strings ");
    strcat (str,"are ");
    strcat (str,"concatenated.");

    //
    //  Send the buffer back to NodeJS with the result of our calculation.
    //
    info
    .GetReturnValue()
    .Set(
        NewBuffer((char *) str, 80)
    .ToLocalChecked());
}

//
//  The constructor
//
NAN_MODULE_INIT(Init)
{
    //
    //  Expose the method or methods to NodeJS
    //
    Nan::Set(
        target,
        New<String>("combine").ToLocalChecked(),
        GetFunction(New<FunctionTemplate>(Combine)).ToLocalChecked()
    );
}

//
//  Load the constructor
//
NODE_MODULE(basic_nan, Init)

When I send back to NodeJS my char variable, I get 80 Bytes, but they are full of random values. It looks as if the place where the str variable was pointing got reclaimed before creating a NewBuffer().

My questions

I would like to get an explanation on what is going on, and ideally get a potential solution 🙂.


Solution

  • I think the problem is that char str[80]; will be allocated in the stack and once your Combine method is finished it will be deallocated(popped from the stack) and overwritten with other stuff that gets pushed into the stack.

    Declare it as char* str; and allocate it dynamically with str = new char[80];. Then do all those initializations with strcpy and strcat.