[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

is there memory corruption here?

Bob Doe

9/11/2008 1:16:00 AM

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();

SomeFunc(data, strlen(data));
//do something else

}
2 Answers

Rolf Magnus

9/11/2008 4:21:00 AM

0

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
>
> }


???

9/11/2008 5:26:00 AM

0

Bob Doe ??:
> 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();
>
> SomeFunc(data, strlen(data));
> //do something else
>
> }

Why you use stringstream and const char * together?

the std::stringstream::str() return an temp std::string object, which is destroyed after that line.
you'd better do it like this:

std::string data;
std::stringstream buf;

buf << "some string";
buf << some_int;
data = buf.str();

SomeFunc(data.c_str(),data.length());