little_planet
little_planet

Reputation: 1035

C++: Overwrite std::string in Cache

I got a string variable (contains passphrase) and would like to overwrite it's value with a sequence of '0' before the variable is released. I tought about doing something like:

void overwrite(std::string &toOverwrite){
    if(toOverwrite.empty())
        return;
    else{
        std::string removeString;
        size_t length = toOverwrite.size();
        for(int i = 0; i < length; i++){
            removeString += "0";
        }
       toOverwrite = removeString;
    }    
}

But somehow this doesn't feel right.

  1. First because it seems to produce much overhead in the for loop.
  2. Moreover I'm not sure if the last line would really overwrite the string. I know that e.g. in Java strings are immutable and therefore can not be overwritten at all. They are not immutable in C++ (at least not std::string) but would toOverwrite = removeString really replace toOverwrite or just make that the "pointer" of toOverwrite will point to removeString?
  3. Is it possible that my compiler will optimize the code and removes this overwriting?

Maybe I should use the std::string::replace method or change the datatype to char* / byte[]?

Upvotes: 0

Views: 744

Answers (1)

Tom Tanner
Tom Tanner

Reputation: 9354

Chances are that will just swap and free pointers, leaving the passphrase somewhere in memory which is no longer pointed to. If you want to overwrite the string data, do:

std::fill(toOverwrite.begin(), toOverwrite.end(), '0');

And you don't need a test for an empty string either.

Upvotes: 2

Related Questions