How to properly free a std::string from memory

C++String

C++ Problem Overview


What's the best way to delete an std::string from memory allocated on the heap when I'm done using it? Thanks!

C++ Solutions


Solution 1 - C++

std::string is just a normal class1, so the usual rules apply.

If you allocate std::string objects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically.

int MyUselessFunction()
{
    std::string mystring="Just a string.";
    // ...
    return 42;
    // no need to do anything, mystring goes out of scope and everything is cleaned up automatically
}

The only case where you have to do something is when you allocate an std::string on the heap using the new operator; in that case, as with any object allocated with new, you have to call delete to free it.

int MyUselessFunction()
{
    // for some reason you feel the need to allocate that string on the heap
    std::string * mystring= new std::string("Just a string.");
    // ...
    // deallocate it - notice that in the real world you'd use a smart pointer
    delete mystring;
    return 42;
}

As implied in the example, in general it's pointless to allocate a std::string on the heap, and, when you need that, still you should encapsulate such pointer in a smart pointer to avoid even risking memory leaks (in case of exceptions, multiple return paths, ...).


  1. Actually std::string is defined as

     namespace std
     {
         typedef std::basic_string<char> string;
     };
    

    so it's a synonym for the instantiation of the basic_string template class for characters of type char (this doesn't change anything in the answer, but on SO you must be pedantic even on newbie questions).

Solution 2 - C++

std::string foo("since it's on the stack, it will auto delete out of scope");

or:

std::string* foo = new std::string("allocated on the heap needs explicit destruction")
delete foo;

Solution 3 - C++

Use delete if it's on the heap, and nothing at all if it's on the stack.

Solution 4 - C++

void foo() {
    string* myString = new string("heap-allocated objects are deleted on 'delete myString;'");
    cout << *myString << endl;
    delete myString;
}

or better yet, avoid pointers when possible and use automatic variables:

void foo() {
    string myString("stack-allocated string is automatically deleted when myString goes out of scope");
    cout << myString << endl;
}

Solution 5 - C++

just treat std::string as any basic type.

std::string *str = new std::string("whatever");
///code
delete str;

Solution 6 - C++

Maybe your dealing with really freeing the internal string buffer?

For performance reason, most implementation keep the internal buffer allocated, even is the string is "emptied". Additionally: small strings (smaller than sizeof(ptr)) are directly stored in the area that hold pointers. Theses bytes can never be reclaimed during the life of the string.

To free the internals: the classical trick is to use swap within a scope. This force buffer to be really freed (Works also with vector/map/ostream/stringstream etc ...):

string s;												// size==0 and capacity==15 as the default proxy of the container (help perf on small string)
s = "Looooooooooooooooooooooooooooooong String";		// size==41 and capacity==47 bytes allocated
s.clear();												// size==0  BUT capacity==47 bytes STILL allocated!!
        
s = "Looooooooooooooooooooooooooooooong String";		// size==41 and capacity reuse 47 bytes still allocated. 
s.resize(0);											// size==0  BUT capacity==47 bytes STILL allocated!!
// swap with scope to force freeing string internals
{ 
   	string o;
   	o.swap(s);
}														// size==0 AND capacity==15 (back to smallest footprint possible)
s = "12345";											// size==5 AND capacity==15 (the string is IN the container, no new alloc)

Solution 7 - C++

You can treat std::string like any other class. Use new for allocation, and delete once you're done with it. With C++11, I do not recommend usage of new and delete in most cases. If you need to allocate the string on heap, use std::shared_ptr to wrap it:

std::shared_ptr<std::string> my_string = std::make_shared<std::string>(std::string("My string"));

As soon as all the copies of my_string go out of scope, the associated memory is going to be deleted automatically.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbbosakView Question on Stackoverflow
Solution 1 - C++Matteo ItaliaView Answer on Stackoverflow
Solution 2 - C++The Communist DuckView Answer on Stackoverflow
Solution 3 - C++Oliver CharlesworthView Answer on Stackoverflow
Solution 4 - C++Lie RyanView Answer on Stackoverflow
Solution 5 - C++yu quanView Answer on Stackoverflow
Solution 6 - C++Gordon88View Answer on Stackoverflow
Solution 7 - C++user4580891View Answer on Stackoverflow