I have this function in my program
const char* Graph::toChar() {
std::string str;
const char* toret;
str = "";
for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
str += (*it)->toString();
}
toret = str.c_str();
return toret;
}
Then I’m debugging the function everything works properly until I’m in return toret; line. I press step over and the debugger is going to std::string str; line and all string and charater variables become “”, so the final return of the function is “” (nothing).
What am I doing wrong?
*(it)->toString(); is working properly and when the debugger executes *toret = str.c_str();* the value in toret is correct.
Thx
What you’re doing here is bad: You are returning the
c_strof anstd::stringthat’s about to be deleted when it goes out of scope. regardless of debug mode or not, this means unpredictable behavior. actually rather predictable – your program will crash 🙂You should either return
const std::string, acceptstd:string &as an argument and build it, or usestrdup()to copy the string’s c_str to something that will stay in memory. Keep in mind that using strdup() means you’ll have to delete it somewhere later.Here are two forms of the function that will work:
or