Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ does returning a string created from a local char array cause a memory leak or undefined behavior?

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?

like image 645
Jimmy Johnson Avatar asked Feb 18 '23 11:02

Jimmy Johnson


1 Answers

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.

like image 116
Jørgen Fogh Avatar answered May 15 '23 00:05

Jørgen Fogh