Reputation: 61
I have some security critical code, and I'd like to make sure that sensitive buffers are always erased before being freed. I can implement a buffer class which calls memset_s in its destructor, but perhaps there is a more convenient way.
If I replace std::allocator with a variant that calls memset_s in deallocate(), will that force std::vector not to allocate T objects anywhere else except as temporaries?
Thanks.
Upvotes: 3
Views: 864
Reputation: 208456
The allocator is a template argument, if you decide to implement one for your particular use case it will be active only in those objects for which you explicitly opt into this allocator:
std::vector<T,SecureAllocator> v; // this uses the memset_s under the hood
std::vector<T> n; // this doesn't
Now, the allocator modifies the type of the object, which means that if you have functions that take std::vector<T>
as arguments you will not be able to pass a std::vector<T,SecureAllocator>
.
Alternatively, you could implement a polymorphic allocator in which the source of the memory can be controlled at runtime. That is supported in BSL (an implementation of the C++03 standard library available in github), in which case the vectors are of the same type even if they allocate from different sources:
bsl::vector<T> v(bslma::Default::allocator());
// bslma::Default::allocator() is new/delete
bsl::vector<T> n(secureAllocator());
Upvotes: 2
Reputation: 180245
There are two reasons why you could have such T objects: either as elements of the vector, or for other reasons.
They can't be elements of the vector as that would violate contiguity, as well as violate the no-throw guarantee for swap
. If you have elements for other reasons, they'd have to be constructed with observable complexity. Additionally T::T()
may not be available (DefaultConstructable
isn't required) or it might throw which would be an observable effect as well.
So, in general vector
cannot have "hidden" elements.
Upvotes: 2