0

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());
}
Ron
  • 14,674
  • 4
  • 34
  • 47
  • 1
    Don't use `new`, don't use C-style casts, don't use `const_cast` *especially* to modify the variable, don't use C-style strings, don't return pointers to memory that's already deallocated. In fact, I'm fairly sure if it would be easier to start anew than fix this code. – milleniumbug Oct 20 '17 at 09:52
  • for example how should i change my code ? return const_cast(printStream->str().c_str()); – şentürk şimşek Oct 20 '17 at 10:48

2 Answers2

1

Change the return type to std::string and return a std::string object directly.

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
1

I think a function called to_string really, really, really should return a std::string.

And then all this junk can be replaced by

std::string FieldData::to_string() const
{ return "Invalid Field Type"; }
Bo Persson
  • 90,663
  • 31
  • 146
  • 203