c++ - How to cleanse (overwrite with random bytes) std::string internal buffer? -


consider scenario, std::string used store a secret. once consumed , no longer needed, cleanse it, i.e overwrite memory contained it, hiding secret.

std::string provides function const char* data() returning pointer (since c++11) continous memory.

now, since memory continous and variable destroyed right after cleanse due scope end, safe to:

char* modifiable = const_cast<char*>(secretstring.data()); openssl_cleanse(modifiable, secretstring.size()); 

according standard quoted here:

$5.2.11/7 - note: depending on type of object, write operation through pointer, lvalue or pointer data member resulting const_cast casts away const-qualifier68 may produce undefined behavior (7.1.5.1).

that advise otherwise, conditions above (continuous, to-be-just-removed) make safe?

it safe. not guaranteed.

however, since c++11, std::string must implemented contiguous data can safely access internal array using address of first element &secretstring[0].

if(!secretstring.empty()) // avoid ub {     char* modifiable = &secretstring[0];     openssl_cleanse(modifiable, secretstring.size()); } 

Comments