Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > is there memory corruption here?

Reply
Thread Tools

is there memory corruption here?

 
 
Bob Doe
Guest
Posts: n/a
 
      09-11-2008
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

}
 
Reply With Quote
 
 
 
 
Rolf Magnus
Guest
Posts: n/a
 
      09-11-2008
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
>
> }



 
Reply With Quote
 
 
 
 
书呆彭
Guest
Posts: n/a
 
      09-11-2008
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());
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Avoid memory corruption in shared memory used by several processes? Sune C Programming 14 08-26-2007 03:57 AM
Avoid memory corruption in shared memory used by several processes? Sune C Programming 5 07-13-2007 02:29 PM
Microsoft Internet Explorer COM Object Instantiation Memory Corruption Vulnerability Imhotep Computer Security 2 12-15-2005 03:03 PM
iDEFENSE Security Advisory 02.28.05: Mozilla Firefox and,MozillaBrowser Out Of Memory Heap Corruption Design Error winged Computer Security 1 03-02-2005 01:56 AM
memory corruption while debugging Noa Garnett C++ 7 08-25-2004 02:35 PM



Advertisments