Ostrstream unpredicted behavior in VS 2008

S

Saurabh Gupta

ostrstream m_msgStream;
m_msgStream.seekp(0);
m_msgStream << "Hello";
m_msgStream << ends;
char *str = m_msgStream .str();

We are getting str NULL. If we remove the skeep line then it working
fine. Even the same code is working fine with VS 6. Anyidea how to use
seekp in VS 2008?
 
R

Robert Hairgrove

ostrstream m_msgStream;
m_msgStream.seekp(0);
m_msgStream<< "Hello";
m_msgStream<< ends;
char *str = m_msgStream .str();

We are getting str NULL. If we remove the skeep line then it working
fine. Even the same code is working fine with VS 6. Anyidea how to use
seekp in VS 2008?

Why use it at all? At least it is entirely superfluous in the example
code you posted.

Aside from that, you should realize that std::stringstream::str()
returns std::string, not char*. You should be using:

const char *str = m_msgStream.str().c_str();

Please note that modifying the contents of the return value of
std::string::c_str(), as might happen after the above assignment to
non-const char* (which is allowed for legacy reasons on many compilers),
will result in undefined behavior (c_str() returns const char*).
 
R

Robert Hairgrove

ostrstream has been deprecated for a long time already, I would suggest
to switch over to ostringstream.

Oops ... overlooked that one!
He is using ostrstream, where indeed str() returns char*.

Oops again.
With ostringstream this would create a dangling pointer into a destroyed
temporary std::string object!

And yet another oops!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top