brahmaiah
brahmaiah

Reputation: 11

cppcheck complains dangerous use of c_str(). the value returned by c_str() is invalid after this call

char* mstring(char str) {
    std::string mystring = "task:";
    mystring.append(str);
    return (*char)mystring.c_str();//dangerous use of c_str() the value returned by c_str() is invalid after this call
}

Upvotes: 1

Views: 562

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31464

Cppcheck is correct. You are returning a pointer to a char that dies at the end of the function. Don't do that. Return a std::string instead which will be a copy that lives its own life (in the caller).

You want

std::string mstring(char ch) { 
    std::string mystring = "task:";
    mystring.append(ch);
    return mystring;
}

Upvotes: 3

Related Questions