> Calls to memset() run the risk of being optimized out by the compiler.
I would be curious to know which compilers or which options actually still do these ill-fated optimizations?
> Calls to memset() run the risk of being optimized out by the compiler.
I would be curious to know which compilers or which options actually still do these ill-fated optimizations?
char* plain_text = malloc(size);
///do stuff with plain_text
memset(plain_text, 0, size);
free(plain_text);
For most programs that last memset is unnecessary (and may even be unnecessary according to the standard, but it's probably implementation defined, not undefined behavior) and it makes sense for the compiler to optimize it away. But for crypto purposes you have to be afraid of someone being able to read plain_text later, so the memset is importantIt's typically done when you don't need the value anymore, of course. So, the compiler sees a write to memory that is never used. Which is exactly the type of thing compilers try to optimize out (if it can be proven that it is never used).
From the C99 standard:
In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).
1- Try to use SecureZeroMemory() on Windows
2- Use memcpy_s() if available, which from its manpage is guaranteed not to be optimized away by compilers
3- Use a loop to manually zero-out the buffer after having casted to a volatile pointer, again to prevent compiler optimizations