Well, p
does not point to a 0-terminated string if get_string()
returns NULL; that's the problem here, since the std::string
constructors that take a pointer to 0-terminated C string cannot deal with NULL, which is as much a 0-terminated C string as two dozens of bananas are.
So, if get_string()
is your own function, as opposed to a library function, then maybe you should make sure that it cannot return NULL. You could for instance let it return the sought std::string
itself, since it knows it's own state. Otherwise, I'd do this, using the Cleanup
from this answer as a helper to guarantee that p
cannot leak (as suggested by Martin York in a comment):
string foo()
{
const char* p = get_string();
const Cleanup cleanup(p);
const std::string str(p != NULL ? p : "");
return str;
}