468,272 Members | 2,046 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,272 developers. It's quick & easy.

is there memory corruption here?

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

}
Sep 11 '08 #1
2 1709
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

}

Sep 11 '08 #2
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());
Sep 11 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Noa Garnett | last post: by
10 posts views Thread by eyh5 | last post: by
8 posts views Thread by ranjeet.gupta | last post: by
4 posts views Thread by Harsha | last post: by
4 posts views Thread by T Clancey | last post: by
14 posts views Thread by =?Utf-8?B?UHVjY2E=?= | last post: by
2 posts views Thread by Fredo | last post: by
66 posts views Thread by Why Tea | last post: by
reply views Thread by zattat | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.