std::string.c_str() returning a weird characters

主宰稳场 提交于 2019-12-25 02:57:56

问题


In my project, I use to load textures by specifying its file name. Now, I made this function const char* app_dir(std::string fileToAppend); that returns the mains argv[0] and change the application name by the fileToAppend. Since I cannot make the string manipulation easy with a char*, I use the std::string. My texture loader takes a const char* for file name so need to switch back to c_str(), now it generates a sequence of ASCII symbol characters (bug). I already fix the problem by changing the return type of the app_dir() to std::string. But why is that happening?

EDIT

sample code:

//in main I did this

extern std::string app_filepath;

int main(int argc, char** arv) {

    app_filepath = argv[0];

    //...

}

//on other file

std::string app_filepath;

void remove_exe_name() {

    //process the app_filepath to remove the exe name

}

const char* app_dir(std::string fileToAppend) {

    string str_app_fp = app_filepath;

    return str_app_fp.append(fileToAppend).c_str();

    //this is the function the generates the bug

}

I already have the functioning one by changing its return type to std::string as I said earlier.


回答1:


A big no no :) returning pointer to local objects

return str_app_fp.append(fileToAppend).c_str();

Change your function to

std::string app_dir(const std::string& fileToAppend) {

string str_app_fp = app_filepath + fileToAppend;

return str_app_fp;

}

And on the return value use c_str()




回答2:


When you using function const char* app_dir(std::string fileToAppend); you get pointer to the memory that allocated on the stack and already deleted when the function ends.



来源:https://stackoverflow.com/questions/15449544/stdstring-c-str-returning-a-weird-characters

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