0

I have a class that contains a a string. Currently, it's an std::wstring but does not have to be. I had read here that std::string should not be used but I am wondering if something like this would work:

if (aString.length() == aString.capacity() )
{
    std::wstring oldString = aString;
    aString = wstring(aString);
    aString.reserve(PREALLOCATION_AMOUNT);
    SecureZeroMemory((PVOID)oldString.c_str(),oldString.size());
    oldString.clear();
}

would this basically equate to a secure realloc of the string buffer? If not is there a better solution?

Community
  • 1
  • 1
Ray Pendergraph
  • 449
  • 5
  • 19

2 Answers2

0

It's not guaranteed that c_str() will point to the original buffer and not make a copy. That's probably the way it works, but there's no way to be sure without looking at your specific implementation of basic_string.

There are enough potential problems with making std::wstring secure that I'd avoid it entirely and find a secure string class or write my own.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

I don't know if this would actually work, but perhaps you could try this:

#include <algorithm>
#include <string>

// ...

std::string password = "sekrit";
std::fill(password.begin(), password.end(), 0);

Of course, this assumes that your string is never resized. If it is, you will lose access to the memory where the beginning of the string WAS stored. As has been pointed out by others, it's probably a bad idea.

Wug
  • 12,956
  • 4
  • 34
  • 54