I have this code block as written with strstream
. And I converted it to sstream
as below. I'm not sure, but I think printStream->str()
is returning a string object with a copy (temporary) of the contents in the stream buffer pointed by printStream
, and then then you are invoking c_str()
on it and getting a const char *
, and then casting away the const-ness, and then returning the pointer outside the function scope. I think since its a temporary value you are getting back from printStream->str()
, you will be using a pointer to deallocated memory outside this function. How should I do this?
char * FieldData::to_string() const
{
if(printStream)
return printStream->str();
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostrstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << '\0';
return printStream->str();
}
char * FieldData::to_string() const
{
if(printStream)
return const_cast<char *>(printStream->str().c_str());
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostringstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << '\0';
return const_cast<char *>(printStream->str().c_str());
}
I think a function called
to_string
really, really, really should return astd::string
.And then all this junk can be replaced by
Change the return type to
std::string
and return astd::string
object directly.