What happens in this code is:
const char * returnCharPtr()
{
std::string someString("something");
return someString.c_str();
}
- instance of
std::string
is created – it is an object with automatic storage duration - pointer to the internal memory of this string is returned
- object
someString
is destructed and the its internal memory is cleaned up - caller of this function receives dangling pointer (invalid pointer) which yields undefined behavior
The best solution is to return an object:
std::string returnString()
{
std::string someString("something");
return someString;
}
When calling your function, DO NOT do this:
const char *returnedString = returnString().c_str();
because returnedString
will still be dangling after the returned std::string
is destructed. Instead store the entire std::string
:
std::string returnedString = returnString();
// ... use returnedString.c_str() later ...