Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zeroing memory used by STL containers

Tags:

c++

I'd like to use STL containers (plus std::basic_string) to temporarily store keys or passwords in memory, and I'd like to zero the memory when done.

I was initially planning to use STL containers parameterized on a custom allocator that zeroes memory in allocator::deallocate, but I'm presuming that containers are allowed to use memory that doesn't come from the specified allocator. For example, it seems reasonable for a std::vector or a std::string to contain a fixed-size array member meant for small allocations.

Am I rightly concerned, and should I (sigh) write my own container?

like image 228
jamesdlin Avatar asked Aug 08 '12 20:08

jamesdlin


People also ask

Does empty vector allocate memory?

There is another workaround to free the memory taken by the vector object. The idea is to swap the vector with an empty vector (with no memory allocated). This will de-allocate the memory taken by the vector and is always guaranteed to work. That's all about deleting vector contents and free up memory in C++.

Is STL container thread safe?

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.

How much memory does a vector use?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient. However, both std::set and std::unordered_set use nearly an order of magnitude more memory than would be strictly necessary.


2 Answers

I would use std::vector with a custom allocator that does the zero'ing out. According to the answer at May std::vector make use of small buffer optimization?, it cannot use the small buffer optimization, and hence, with a custom allocator, you should be safe.

If you take it a step further, and use that allocator to allocate the vector, and then use a smart pointer to ensure it's proper release (or do it manually), even the internal contents of the vector (such as the size) will be wiped out.

like image 111
Dave S Avatar answered Nov 15 '22 22:11

Dave S


You can do this by allocating the string/vector using raw memory and placement new and when you're done with it, call the destructor, zero memory, and deallocate raw memory.

like image 32
Dani Avatar answered Nov 15 '22 22:11

Dani