简体   繁体   中英

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 🙂.

According to the documentation , NewBuffer assumes that the ownership of the data is transferred to the buffer itself.
You char array is not copied at all, it disappears when it goes out if its scope and you are thus incurring in an undefined behavior.
You should rather allocate the array on the dynamic memory and let the buffer takes the ownership of it to solve the problem.
In other terms, use the new operator to allocate the array of chars, pass it to NewBuffer and don't delete it .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM