简体   繁体   中英

Bad value in function returning string and const char*

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_str of an std::string that'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 , accept std:string & as an argument and build it, or use strdup() 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:

const std::string Graph::toChar() {
    std::string str;
    for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
        str += (*it)->toString();
    }
    return str;
}

or

void Graph::toChar(std::string &out) {
    out = ""
    for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
        out += (*it)->toString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM