David Gatti David Gatti - 11 months ago 49
C++ Question

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
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.
NewBuffer((char *) str, 80)

// The constructor
// Expose the method or methods to NodeJS

// 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
variable was pointing got reclaimed before creating a

My questions

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

Answer Source

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.