0

I convert the stringstream's string to char pointer but it writes empty string. Why does it fail?

std::stringstream ss;
ss << "de12mu";
char* msg = (char*)ss.str().c_str();
std::cout << "msg: " << msg << " " << strlen(msg) << std::endl;
xyzt
  • 1,201
  • 4
  • 18
  • 44
  • 1
    Undefined behaviour if I ever saw it. By the way, first related question on the right: http://stackoverflow.com/questions/1374468/c-stringstream-string-and-char-conversion-confusion?rq=1 – chris Aug 02 '13 at 07:39

1 Answers1

1

It's because your call to ss.str() returns a temporary string, and when you then get a pointer to that temporary string it will not be valid after the statement is done.

Using that pointer after the temporary string is destroyed is undefined behavior.

Also note that the c_str function returns const char*.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621