I am storing some sensitive information like passwords in std::string. I want to know if there is a guaranteed way to clear the memory where the actual data was stored ?
Asked
Active
Viewed 194 times
2
-
1Overwrite it? Alternatively depending on your exact requirements a costom allocator overwriting the memory may do the trick. After you give the ownership of the memory back to the OS, there's no way afaik to be sure the data is overwritten before it may be assigned to a different process or another part of the current one. – fabian Apr 19 '22 at 17:22
-
1@fabian: Any reasonable modern OS ought to guarantee that; it would be a serious security bug to leak memory contents of one process to another. Pages are zeroed before any other process gets to see them. The usual concern is that the data might have been written out to a swap device (in which case clearing is not guaranteed to overwrite it), or that an exploit elsewhere in the same program might be able to read the contents. – Nate Eldredge Apr 19 '22 at 17:28
-
2`std::string` is a suboptimal choice for storing sensitive stuff, since it's very easy to accidentally get copies of the string all over the place in memory (copying strings, assigning to strings, concatenating, `reserve`, `shrink_to_fit`, `substr`, etc... can all cause reallocations -> copies) - additionally using a custom allocator to override the memory won't always work (due to most implementations having a small string optimization). So if it's sensitive stuff you probably want your own class that makes sure your secret isn't copied around in memory at all (and erases it once it's done). – Turtlefight Apr 19 '22 at 17:47