简体   繁体   中英

Zeroing memory used by STL containers

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?

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.

您可以通过使用原始内存和placement new分配字符串/向量来完成此操作,当您完成它时,调用析构函数,零内存并释放原始内存。

Use a custom string class that zeros the memory buffer in its destructor.

class zeroed_string : public std::string
{
public:
    ~zeroed_string()
    {
        for (int i = 0; i < size(); ++i)
            (*this)[i] = 0;
    }
// ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM