I have to write a Windows service that handles at some point confidential data (such as PIN codes, passwords, and so on). Those informations are needed for a very short amount of time: usually they are sent almost immediately to a smart card reader.
Lets consider this piece of code:
{
std::string password = getPassword(); // Get the password from the user
writePasswordToSmartCard(password);
// Okay, here we don't need password anymore.
// We set it all to '' so it doesn't stay in memory.
std::fill(password.begin(), password.end(), '');
}
Now my concern is about compiler optimizations. Here the compiler might detect that password is about to be deleted and that changing its value at this point is useless and just remove the call.
I don't expect my compiler to care about the value of future-unreferenced memory.
Are my concerns legitimate ? How can I be sure that such a piece of code won't be optimized-out ?
See Question&Answers more detail:os