title: How to cleanse (overwrite with random bytes) std::string internal buffer?
body: <p>Consider a scenario, where <code>std::string</code> is used to store <em>a secret</em>. Once it is consumed and is no longer needed, it would be good to cleanse it, i.e overwrite the memory that contained it, thus hiding the <em>secret</em>.</p>
  
  <p><code>std::string</code> provides a function <code>const char* data()</code> returning a pointer to (since C++11) continous memory. </p>
  
  <p>Now, since the memory is continous <strong>and</strong> the variable will be destroyed right after the cleanse due to scope end, would it be safe to:</p>
  
  <pre><code>char* modifiable = const_cast&lt;char*&gt;(secretString.data());
  OpenSSL_cleanse(modifiable, secretString.size());
  </code></pre>
  
  <p>According to standard quoted here:</p>
  
  <blockquote>
    <p>$5.2.11/7 - Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a <code>const_cast</code> that casts away a <code>const-qualifier</code><sup>68</sup> may produce undefined behavior (7.1.5.1).</p>
  </blockquote>
  
  <p>That would advise otherwise, but do the conditions above (continuous, to-be-just-removed) make it safe?</p>