Just calling free() on allocated memory doesn't clear the data from RAM and neither do stack pop operations and can be recovered by RAM dump AFAIK. I thought of just setting sensitive data to zero in destructors but the compiler likes to optimise away unused values. For security sensitive applications, is there any way to prevent that apart from disabling optimisations? Or even better, some compiler flag or system call that automatically zeroes used memory upon program exit?
Asked
Active
Viewed 112 times
4
-
Related: [Do compilers optimize memset in destructor?](https://stackoverflow.com/q/41502725/11082165). See also the notes on [`std::memset`'s cppreference page](https://en.cppreference.com/w/cpp/string/byte/memset) for ways to ensure that memory fills aren't optimized away. – Brian61354270 Feb 27 '23 at 18:40
-
related/dupe: https://stackoverflow.com/questions/42771298/explicitly-removing-sensitive-data-from-memory, https://stackoverflow.com/questions/10683941/clearing-memory-securely-and-reallocations, https://stackoverflow.com/questions/5698002/how-does-one-securely-clear-stdstring – NathanOliver Feb 27 '23 at 18:40
-
1You probably want to zero on free, not just on exit. Data can persist for several minutes after physical removal of power, and physical removal of power will stop any `atexit` routines from running. In short, zero sensitive data as soon as you can, don't wait for exit. – Ben Feb 27 '23 at 19:45
-
See @Brian comments for suggestions. – Ben Feb 27 '23 at 19:46
-
@Brian, looks like a good answer to me. – Ben Feb 27 '23 at 19:48
-
1Also note that you have to `mlock` or else you risk the sensitive data being written to swap, which is even more persistent. – Nate Eldredge Feb 28 '23 at 02:56