Automatic memory deallocation by std::string ??

Discussion in 'C++' started by qazmlp, Mar 7, 2004.

  1. qazmlp

    qazmlp Guest

    Is there a memory leak here? Can't the memory deallocation happen
    automatically as the std::string object anyway is owning the memory?
    #include <cstring>
    #include <string>
    #include <iostream>

    char* toString()
    {
    const char* cStr = "cStr" ;
    char* ptr = new char[ std::strlen( cStr ) + 1 ] ;
    std::strcpy( ptr , cStr ) ;

    return ptr ;
    }

    int main()
    {
    std::string cppStr( toString() ) ;
    std::cout<< cppStr << std::endl;
    }
    qazmlp, Mar 7, 2004
    #1
    1. Advertising

  2. "qazmlp" <> wrote in message
    news:...
    > Is there a memory leak here?


    Yes

    > Can't the memory deallocation happen
    > automatically as the std::string object anyway is owning the memory?


    But that's the point, std::string does not own the memory. It always
    allocates its own memory.

    > #include <cstring>
    > #include <string>
    > #include <iostream>
    >
    > char* toString()
    > {
    > const char* cStr = "cStr" ;
    > char* ptr = new char[ std::strlen( cStr ) + 1 ] ;
    > std::strcpy( ptr , cStr ) ;
    >
    > return ptr ;
    > }
    >
    > int main()
    > {
    > std::string cppStr( toString() ) ;
    > std::cout<< cppStr << std::endl;
    > }


    john
    John Harrison, Mar 7, 2004
    #2
    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. Replies:
    2
    Views:
    705
    Paavo Helde
    Dec 18, 2004
  2. BigBrian
    Replies:
    12
    Views:
    578
    Pete Becker
    Apr 7, 2005
  3. Nicolas Matringe

    std.textio, readline and memory deallocation

    Nicolas Matringe, Sep 1, 2006, in forum: VHDL
    Replies:
    9
    Views:
    2,049
    Paul Uiterlinden
    Sep 4, 2006
  4. pasa_1
    Replies:
    19
    Views:
    507
    David Harmon
    Nov 2, 2006
  5. madhu
    Replies:
    6
    Views:
    621
    madhu
    Nov 13, 2006
Loading...

Share This Page