Rolf Magnus
9/11/2008 4:21:00 AM
Bob Doe wrote:
> I've been told there is memory corruption for buf.str().c_str() Can
> someone explain why?:
>
> void myFunc()
> {
> std::stringstream buf;
> buf << "some string";
> const char *data = buf.str().c_str();
str() returns a string by value, meaning you are calling c_str() on a
temporary string value that is destroyed after this line. The array that
the pointer returned by c_str() points to is only valid as long as the
string does exist (and isn't modified). So after that line, data is a
dangling pointer that you must not dereference anymore.
> SomeFunc(data, strlen(data));
> //do something else
>
> }