Mohammad Abu Musa Mohammad Abu Musa - 2 months ago 18x
C++ Question

c_str() returns empty string

For some reason c_str() returns empty string, the parameter

const chart**out_function
will hold a method name for file operations like
so basically what I do is converting a string I have to c_str() but I get an empty string below is how I do the calls

In this part I just prepare a dictionary with an operation name, as you can notice I am just sending "fopen" as string

pp::VarDictionary fileOp;
pp::VarArray args;
args.Set(0, "filename.txt");
args.Set(1, "wb");
fileOp.Set("args", args);
fileOp.Set("cmd", "fopen");

This function will parse the dictionary sent above and return the name of the function in

int ParseMessage(pp::Var message, const char** out_function,
pp::Var* out_params) {

I use this line of code to convert the string to c_string, but It returns empty text

*out_function = cmd_value.AsString().c_str();

here is the full code, it is based on Google Native Client but at the same time it is standard C/C++ code


The result of c_str() is only valid as long as the std::string object that produced that result is valid.

In your case, AsString() call produces a temporary std::string object which is then immediately destroyed. After that the result of that c_str() call no longer makes any sense. Trying to access the memory pointed by that pointer leads to undefined behavior.

Don't attempt to store the pointer returned by c_str(). If you need that string as a C-string for an extended period of time, allocate memory buffer for it yourself and copy the result of c_str() to that buffer.

Another (much better) idea would be not to rush the conversion to C-string. Return the result as std::string and call c_str() on it at the very last moment: when you reall really really need a C-string.