-2

So why would this be able to remove the string content from memory or not? I dont understand this?

  • 4
    You're asking us about code that isn't even real code. So, the direct answer to your title question would be, "No, because it isn't valid C++ code and won't even compile, much less run and do what you *seem* to be trying." What is your *real* problem that you're trying to solve ? – WhozCraig Oct 22 '20 at 02:53
  • the real question is this base on the above pseudocode, would the contents of the PWD be cleared from memory? – smart panda Oct 22 '20 at 03:07
  • 1
    The *final* contents of `PWD`, sure. No guarantees whatsoever that the PWD isn't sitting somewhere in cleartext in memory anyway, however. at least some portion of it. During string building it is entirely feasible that reallocations transpired to expand the dynamic buffer in PWD, and in so doing, leaving entrails of the pre-expanded buffer. The naive approach in the posted algorithm does nothing to safeguard that. If you want to do this right use a custom allocator class for `std::basic_string` that zero-fills memory on dealloc (or even random-fills). – WhozCraig Oct 22 '20 at 03:10
  • 2
    No, you can't prevent the string's memory from being copied around without you knowing. If you want to mark memory as secure, you need to use OS-specific facilities. See https://stackoverflow.com/questions/16500549/how-to-keep-c-variables-in-ram-securely – Nikos C. Oct 22 '20 at 03:11
  • Technically, no, this pseudocode would *replace* the content of `pwd` with spaces. At that point, the content consists of some number of spaces, which reside in memory. *A more precise question is more likely to generate the type of answer you seek. It would also make the question more likely to be found by the next person with the same question.* – JaMiT Oct 22 '20 at 03:31

1 Answers1

2

Why would this not remove String data from memory

Because nothing requires it to. An implementation has no obligation to ensure the string isn't left in memory somewhere.

It's important to understand that this is true whether or not you can think of a way it can go wrong. It can go wrong even if you can't think of a way it can fail. But here, there's two obvious ways it can fail:

  1. The string may need to enlarge its buffer, leaving the smaller buffer still containing the contents of the string.

  2. The optimizer may discover that the string isn't accessed after being replaced with spaces and simply remove that code since it has no observable consequences.

David Schwartz
  • 166,415
  • 16
  • 184
  • 259