Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a C++ std::string object safe from memory leaks?

I'm fairly novice with C++'s strings so the following pattern may be a little fugly. I'm reviewing some code I've written before beginning integration testing with a larger system. What I'd like to know is if it is safe, or if it would be prone to leaking memory?

string somefunc( void ) {
    string returnString;
    returnString.assign( "A string" );
    return returnString;
}

void anotherfunc( void ) {
    string myString;
    myString.assign( somefunc() );
    // ...
    return;
}

The understanding I have is that the value of returnString is assigned to a new object myString and then the returnString object is destroyed as part of resolving the call to somefunc. At some point in the future when myString goes out of scope, it too is destroyed.

I would have typically passed a pointer to myString into somefunc() and directly assigned to values to myString but I'm striving to be a little clearer in my code ( and relying on the side effect function style less ).

like image 436
Stephen Avatar asked Aug 22 '11 15:08

Stephen


People also ask

Are memory leaks permanent C++?

Memory leaks don't result in physical or permanent damage. Since it's a software issue, it will slow down the applications or even your whole system. However, a program taking up a lot of RAM space doesn't always mean its memory is leaking somewhere. The program you're using may really need that much space.

How are memory leaks caused in C++?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.

Are memory leaks OK?

You allocate the memory, work with it until the program terminates. This is not a memory leak; it doesn't impair the program, and all the memory will be scavenged up automagically when the program terminates. Generally, you should avoid memory leaks.


1 Answers

Yes, returning a string this way (by value) is safe,albeit I would prefer assigning it this way:

string myString = somefunc();

This is easier to read, and is also more efficient (saving the construction of an empty string, which would then be overwritten by the next call to assign).

std::string manages its own memory, and it has properly written copy constructor and assignment operator, so it is safe to use strings this way.

like image 127
Péter Török Avatar answered Oct 27 '22 07:10

Péter Török