Problem

Is it safe to return a 'const char *' from a local std::string?

Solution

If i have code like this:


const char* ACSPorts::getLogPort()
{
   std::string realOutput;
   ........
   return realOutput.str().c_str();
}

then you are in troubles!

The code is wrong, even though is might work with some compiler versions. For example it was working with gcc 3.3 but it is not working with gcc 3.4.

In a nutshel, we return a pointer to memory managed by the realOutput local string. But when we get out of scope realOutput is deleted and it takes with it the buffer pointed by our return pointer.

For more details see the following links: http://groups.google.de/group/borland.public.cppbuilder.language/browse_thread/thread/e659763041a543e/6c96e609c96e2dff?lnk=st&q=c_str+return+memory+allocation&rnum=46&hl=de#6c96e609c96e2dff http://groups.google.de/group/comp.lang.c++/browse_thread/thread/4589f8eec56dbffa/057c1970e9227ffc?lnk=st&q=return+local+std::string&rnum=1&hl=de#057c1970e9227ffc This is probably due to changes in the implementation of the std::string class.

It seems to us that the better solution to have easy memory management from the user's point of view is to change the signature of these methods:


str::string ACSPorts::getLogPort()
{
   std::string realOutput;
   ..........
   return realOutput;
}

-- GianlucaChiozzi - 18 Aug 2005

A more efficient solution is to pass in a reference to a string object which avoids string copies on the stack.
This is a well-known efficiency for C++.


void ACSPorts::getLogPort(str::string &returnStr)
{
   std::string realOutput;
   ..........
   returnStr = realOutput;
}

Better yet, just use returnStr directly avoiding the copy of realOutput to returnStr.

If there are no performance concerns, because the function is seldomly used, the other solution might be more convenient the return string is directly avaible for indirection operations on the same line of code.