Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::string::clear and std::list::clear erases data from memory

Tags:

c++

string

list

In the description of the string::clear function, it says:

clear: Erases the contents of the string, which becomes an empty string (with a length of 0 characters).

In the description of the list::clear function, it says:

clear: Removes all elements from the list container (which are destroyed), and leaving the container with a size of 0.

Does the clear overwrite the memory of the string and the list or just free them?

like image 910
Kam Avatar asked Jul 10 '13 19:07

Kam


People also ask

Does std::string clear free memory?

Problem Description. The String::clear() function does only set the length to 0, it does not free the memory.

Does vector clear deallocate memory?

No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory.

Does vector clear delete objects?

std::vector does call the destructor of every element it contains when clear() is called. In your particular case, it destroys the pointer but the objects remain.

What is std::string data?

The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.


2 Answers

Neither function is required to overwrite the erased data.

like image 124
Pete Becker Avatar answered Oct 06 '22 06:10

Pete Becker


The memory isn't overwritten. It is not even guaranteed to be freed.

For example, if you create a huge string and call clear on it, only its size will be reduced, but the allocated memory may still be reserved. However, it will be freed if the string gets out of scope.

std::list at least guarantees that the elements inside the list will be destructed if you clear the list.

So, if your memory contains sensitive data, you should manually overwrite them.

like image 36
Philipp Claßen Avatar answered Oct 06 '22 08:10

Philipp Claßen