Automatic memory deallocation by std::string ??

Q

qazmlp

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;
}
 
J

John Harrison

qazmlp said:
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
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top