-3

For some reason c_str() returns empty string, the parameter const chart**out_function will hold a method name for file operations like fopen 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 out_function and args in out_params

    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

http://pastebin.com/S4P8aZqL

4
  • You are storing a pointer to a destroyed temporary. Commented Aug 17, 2016 at 21:25
  • 2
    Don't spam tags. There is no language "C/C++" and the snippets are clearly C++, not C. Commented Aug 17, 2016 at 21:30
  • It relates to all three of them, I am not trying to spam Commented Aug 17, 2016 at 21:31
  • @MohammadAbuMusa Coding in C++ is not sufficient reason to tag C. You're using std::string, namespaces, and OOP. That's not C. Commented Aug 17, 2016 at 22:02

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer, here is the code I used to solve this issue *out_function = strdup(cmd_value.AsString().c_str());
@Mohammad Abu Musa: That will solve it, but now you have a malloced block of raw memory to manage manually. As I said, a much better idea would be to switch to using std::string until the last moment.
Thanks, I just did that, I think using std::string is a much better approach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.