Is it a good idea to return " const char * " from a function?

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


Solution 1:

Depending on what somestlstring is and what is being done there.

If it is a local variable you are returning a pointer into memory that is being released when GetSomeString completes, so it is a dangling pointer and an error.

It all boils down to the lifetime of somestlstring and 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 changes somestlstring from the call to .c_str() and before s is constructed you will be in undefined behavior land.

Solution 2:

If you are asking about the lifetime of the const char * returned by the std::string c_str() function, it is valid until you modify the string you obtained it from, or until the string is destroyed. Returning it from a function is OK (though I would say not great practice), provided you bear those two facts in mind.