0

I don't really understand the behaviour of the ostringstream 's internal buffer considering this snippet :

  ostringstream osTmp;
  osTmp << 6 << "D";
  const char *form1 = osTmp.str().c_str();
  osTmp.str("");
  osTmp.clear();
  osTmp << 7 << "D";
  const char *form2 = osTmp.str().c_str();
  osTmp.str("");
  osTmp.clear();

  cout << form1 << endl;
  cout << form2 << endl;

Here is the output :

6D
7D

Nevertheless, I would have expected that form1 and form2 are not anymore valid pointers....

Thanks a lot for your enlightenments.

Sylvain

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
sylwa06
  • 77
  • 10
  • 1
    This is undefined behavior. It is likely that `osTmp` allocates new strings instead of reusing the previous memory, so the content of the string *happens* to be left in the space. – L. F. Mar 18 '20 at 10:20
  • 1
    Does this answer your question? [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) (The way you invalidate the memory is different, but the underlying issue is the same) – L. F. Mar 18 '20 at 10:21
  • Thanks for your answer. The link concerns more variable scope and stack behavior. Here, we are more on a std::ostringstream internal behavior. But I do agree with you, sounds like we fall into an unpredictable behavior. Cheers ! – sylwa06 Mar 18 '20 at 11:12

0 Answers0