You want to minimize the exposure of data such as passwords and cryptographic keys to local attacks.
You can only guarantee that memory is erased if you declare it to be
at the point where you write over it.
In addition, you must not use an operation such as
) that may silently move sensitive data. In any event, you
might also need to worry about data being swapped to disk; see Recipe
Securely erasing data from memory is a lot easier in C and C++ than it is in languages where all memory is managed behind the programmer’s back. There are still some nonobvious pitfalls, however.
One pitfall, particularly in
C++, is that some API
functions may silently move data behind the
programmer’s back, leaving behind a copy of the data
in a different part of memory. The most prominent example in the
C realm is
), which will sometimes move a piece of memory, updating
the programmer’s pointer. Yet the old memory
location will generally still have the unaltered data, up until the
point where the memory manager reallocates the data and the program
overwrites the value.
Another pitfall is that functions like
may fail to wipe
data because of compiler optimizations.
Compiler writers have worked hard to implement optimizations into their compilers to help make code run faster (or compile to smaller machine code). Some of these optimizations can realize significant performance gains, but sometimes ...