Home > OS >  How to SecureZeroMemory on a string_view?
How to SecureZeroMemory on a string_view?

Time:11-17

With this code:

std::string_view test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory((void*)test.data(), test.length());

I get an exception:

Exception thrown: write access violation.
**vptr** was 0x7FF755084358.

With std::string i get no exception:

std::string test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory((void*)test.data(), test.length());

What I'm doing wrong?

CodePudding user response:

std::string_view is meant to be a read-only view into a string or memory buffer. In your particular example, the string_view is pointing at a read-only string literal, so no amount of casting will make it writable. But, if you do the following instead, then you can modify what a string_view points at, as long as it is being backed by a writable buffer:

char buffer[] = "kYp3s6v9y$B&E)H@";
std::string_view test = buffer;
SecureZeroMemory(const_cast<char*>(test.data()), test.length());

The std::string approach works (and BTW, the type-cast is not necessary) because the string makes a copy of the string literal data into its own internal writable memory buffer, which data() points at.

std::string test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory(test.data(), test.length());
  • Related