我需要编写一个Windows服务,其中涉及一些机密数据(例如PIN码、密码等)。这些信息仅在短时间内需要使用:通常它们会立即发送到智能卡读卡器。
让我们考虑以下代码:
{
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 '\0' so it doesn't stay in memory.
std::fill(password.begin(), password.end(), '\0');
}
现在我关心的是编译器优化。 在这里,编译器可能会检测到密码即将被删除,并且在此时更改其值是无用的,因此会删除该调用。
我不希望我的编译器关心未来未被引用的内存的值。
我的担忧是否合理?我如何确保这样的代码不会被优化删除?
std::string
就是std::basic_string<char, std::char_traits<char>, std::alloc>
。我认为分配器应该是“正确”的位置,并足以安全地处理即将释放的任何内存的清零。 - Christopher Creutzig