Now I have a function that has to return a string. I saw a particular implementation where he returns a const char * from the function.
Something like this:
const char * GetSomeString()
{
........
return somestlstring.c_str();
}
SomeOtherFoo ()
{
const char * tmp = GetSomeString();
string s = tmp;
}
Now I felt there is something potentially wrong with this. Is my gut feel right? or Is this a perfectly safe code?
Kindly give me ur suggestions. I have a feeling return const char * this way might result in havoc..
Thanks,
Arjun
Depending on what
somestlstringis and what is being done there.If it is a local variable you are returning a pointer into memory that is being released when
GetSomeStringcompletes, so it is a dangling pointer and an error.It all boils down to the lifetime of
somestlstringand the operations you perform on it. The pointer returned by.c_str()is guaranteed to be valid only up to the next mutating operation in the string. So if something changessomestlstringfrom the call to.c_str()and beforesis constructed you will be in undefined behavior land.