Search code examples
csecure-coding

Clear variable on the stack


Code Snippet:

int secret_foo(void)
{
  int key = get_secret();
  /* use the key to do highly privileged  stuff */
  ....

  /* Need to clear the value of key on the stack before exit */
  key = 0;      
  /* Any half decent compiler would probably optimize out the statement above */
  /* How can I convince it not to do that? */

  return result;
}

I need to clear the value of a variable key from the stack before returning (as shown in the code).

In case you are curious, this was an actual customer requirement (embedded domain).


Solution

  • You can use volatile (emphasis mine):

    Every access (both read and write) made through an lvalue expression of volatile-qualified type is considered an observable side effect for the purpose of optimization and is evaluated strictly according to the rules of the abstract machine (that is, all writes are completed at some time before the next sequence point). This means that within a single thread of execution, a volatile access cannot be optimized out or reordered relative to another visible side effect that is separated by a sequence point from the volatile access.

     volatile int key = get_secret();