is there memory corruption here?

B

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

}
 
R

Rolf Magnus

Bob said:
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.
 
Ä

书呆彭

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

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top