is there memory corruption here?

Discussion in 'C++' started by Bob Doe, Sep 11, 2008.

  1. Bob Doe

    Bob Doe Guest

    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

    }
     
    Bob Doe, Sep 11, 2008
    #1
    1. Advertising

  2. Bob Doe

    Rolf Magnus Guest

    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
    >
    > }
     
    Rolf Magnus, Sep 11, 2008
    #2
    1. Advertising

  3. 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, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Noa Garnett

    memory corruption while debugging

    Noa Garnett, Aug 24, 2004, in forum: C++
    Replies:
    7
    Views:
    1,808
    Howard
    Aug 25, 2004
  2. Gavin Kreuiter

    Debugger "print" clears memory corruption

    Gavin Kreuiter, Dec 4, 2003, in forum: C Programming
    Replies:
    3
    Views:
    423
    Chris Torek
    Dec 5, 2003
  3. Sune
    Replies:
    14
    Views:
    880
    Chris Thomasson
    Aug 26, 2007
  4. Sune
    Replies:
    5
    Views:
    439
    Darko
    Jul 13, 2007
  5. mohangupta13

    cause of heap corruption here??

    mohangupta13, Sep 12, 2009, in forum: C Programming
    Replies:
    3
    Views:
    389
    Barry Schwarz
    Sep 13, 2009
Loading...

Share This Page