I am wondering if this would cause a memory leak or an undefined outcome in C++?
string foo()
{
char tempArray[30];
strcpy(tempArray, "This is a test");
return string(tempArray);
}
I know this is a bad thing in C but I haven't found a definite answer for C++.
So everyone is saying no, but I am still confused as to when the memory is deallocated?
Lets say I have this method that calls the above method
void bar()
{
string testString = foo();
}
At what point in the above code does the string object returned from foo() call its destructor? Is it immediately after getting copied into the object testString?
What happens in your example is that the constructor with the signature
string ( const char * s );
is called. The constructor allocates new memory for a copy of the string and copies it to that new memory. The string object is then responsible for freeing its own memory when its destructor is called.
When you make a copy of a string, the copy constructor also allocates memory and makes a copy.
You should also take a look at the RAII pattern. This is how string
's memory management works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With