I love the STL
C++ is a great language, specially the STL, templates and generic programming. I love it.
For instance, imagine that you have to wipe some data in vectors after its use. This is common in secure programming, to avoid sensible data to remain in memory longer than really needed.
It’s very easy, just program your own allocator:
#include <memory>
template <class T>
class wiper_allocator : public std::allocator<T>
{
public:
void deallocate(T* p, size_t n) {
// we set memory to zero and the deallocate it
(void) memset(p, 0, sizeof(T)*n);
std::allocator<T>::deallocate(p, n);
};
};
Then, if you are declaring unsigned char vectors this way, for instance:
std::vector<unsigned char> my_vector;
You must just change it like this:
std::vector<unsigned char, wiper_allocator<unsigned char> > my_vector;
And it’s done! Data is automatically wiped on deallocation! You’ll never forget!
You could also wipe data when object is destroyed, but it’s a little bit more resource intensive, and some STL libraries (Microsoft’s for instance) don’t work well this way.
Of course you can improve this one. For instance, you may want to avoid memset, because disassembler tools usually recognize footprints of common functions. You could use your own inline version to make it safer.
You could also also allocate non-swappable memory, so that sensible data is not paged to disk. But this requires non-c++-standard calls to operating system services.
C++ and the STL are huge subjects, but when you get into them, you’ll love them too!
