Is it good secure programming practice to overwrite sensitive data stored in a variable before it is deleted (or goes out of scope)?  My thought is that it would prevent a hacker from being able to read any latent data in RAM due to data-remanence.  Would there be any added security in overwriting it several times?  Here is a small example of what I am talking about, in C++ (with comments included).

void doSecret()
{
  // The secret you want to protect (probably best not to have it hardcoded like this)
  int mySecret = 12345;

  // Do whatever you do with the number
  ...

  // **Clear out the memory of mySecret by writing over it**
  mySecret = 111111;
  mySecret = 0;
  // Maybe repeat a few times in a loop
}


One thought is, if this does actually add security, it would be nice if the compiler automatically added the instructions to do this (perhaps by default, or perhaps by telling the compiler to do it when deleting variables).




  This question was featured as an Information Security Question of the Week.
  Read the Dec 12 2014 blog entry for more details or submit your own Question of the Week.


Yes that is a good idea to overwrite then delete/release the value. Do not assume that all you have to do is "overwrite the data" or let it fall out of scope for the GC to handle, because each language interacts with the hardware differently.
When securing a variable you might need to think about:

encryption (in case of memory dumps or page caching)
pinning in memory
ability to mark as read-only (to prevent any further modifications)
safe construction by NOT allowing a constant string to be passed in
optimizing compilers (see note in linked article re: ZeroMemory macro)

The actual implementation of "erasing" depends on the language and platform. Research the language you're using and see if it's possible to code securely.
Why is this a good idea? Crashdumps, and anything that contains the heap could contain your sensitive data.  Consider using the following when securing your in-memory data

SecureZeroMemory
.NET SecureString
C++ Template

Please refer to StackOverflow for per-language implementation guides.
You should be aware that even when using vendor guidance (MSFT in this case) it is still possible to dump the contents of SecureString, and may have specific usage guidelines for high security scenarios.
