c_str() returns empty string [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-25 19:10:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/39006506/c-str-returns-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!