How to return a std::string.c_str()

What happens in this code is:

const char * returnCharPtr()
{
    std::string someString("something");
    return someString.c_str();
}
  1. instance of std::string is created – it is an object with automatic storage duration
  2. pointer to the internal memory of this string is returned
  3. object someString is destructed and the its internal memory is cleaned up
  4. 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 ...

Leave a Comment