title: Is it possible to guarantee code doing memory writes is not optimized away in C++?
body: <p>C++ compilers are allowed to <a href="https://stackoverflow.com/q/3785366/57428">optimize away writes into memory</a>:</p>
  
  <pre><code> {
       //all this code can be eliminated
       char buffer[size];
       std::fill_n( buffer, size, 0);
   }
  </code></pre>
  
  <p>When dealing with sensitive data the typical approach is using <code>volatile*</code> pointers to ensure that memory writes are emitted by the compiler. Here's how <code>SecureZeroMemory()</code> function in Visual C++ runtime library is implemented (WinNT.h):</p>
  
  <pre><code>FORCEINLINE PVOID RtlSecureZeroMemory(
       __in_bcount(cnt) PVOID ptr, __in SIZE_T cnt )
  {
      volatile char *vptr = (volatile char *)ptr;
  #if defined(_M_AMD64)
      __stosb((PBYTE )((DWORD64)vptr), 0, cnt);
  #else
      while (cnt) {
          *vptr = 0;
          vptr++;
          cnt--;
      }
  #endif
      return ptr;
  }
  </code></pre>
  
  <p>The function casts the passed pointer to a <code>volatile*</code> pointer and then writes through the latter. However if I use it on a local variable:</p>
  
  <pre><code>char buffer[size];
  SecureZeroMemory( buffer, size );
  </code></pre>
  
  <p>the variable itself is not <code>volatile</code>. So according to C++ Standard definition of observable behavior writes into <code>buffer</code> don't count as observable behavior and looks like it can be optimized away.</p>
  
  <p>Now there're a lot of comments below about page files, caches, etc, which are all valid, but let's just ignore them in this question. The only thing this question is about is whether the code for memory writes is optimized away or not.</p>
  
  <p>Is it possible to ensure that code doing writes into memory is not optimized away in C++? Is the solution in <code>SecureZeroMemory()</code> compliant to C++ Standard?</p>