How does one store sensitive data (ex: passwords) in std::string?
I have an application which prompts the user for a password and passes it to a downstr
It is a complicated topic, as an optimizing compiler will work against you. Straightforward approaches like looping over the string and overwriting each character are not reliable, as the compiler might optimize it away. Same with memset, however, C11 added memset_s, which should be secure but might not be available on all platforms.
For that reason, I would strongly recommend to use a trusted crypto library for that task and let their authors take care of portability. Secure wiping is a basic operation (taking a C-array and overwriting it securely), which all libraries will have to implement at some point. Note that the underlying data in a std::string is contiguous (as mandated by the C++11 standard, but in practice even in C++98/03 you could assume it). Therefore, you can use the secure wiping facilities of the crypto library by treading the std::string as an array.
In OpenSSL, secure wiping is provided by the OPENSSL_cleanse function. Crypto++ has memset_z:
std::string secret;
// ...
// OpenSSL (#include and link -lcrypto)
OPENSSL_cleanse(&secret[0], secret_str.size());
// Crypto++ (#include and link -lcrypto++)
CryptoPP::memset_z(&secret[0], 0, secret.size());
As a side-note, if you design the API from scratch, consider avoiding std::string altogether when it comes to storing secrets. It was not a design goal of std::string to prevent leaking the secret (or parts of it during resizing or copying).