title: Writing to default-constructed fstream: Undefined Behavior?
body: <p>Consider the following:</p>
  
  <pre><code>std::basic_fstream&lt;char&gt; testfile;
  testfile.write(reinterpret_cast&lt;const char*&gt;(&amp;someInt), sizeof(int));
  testfile.close();
  </code></pre>
  
  <p>This runs with no complaint when built with VC 8.0, but crashes when built with VC 10.0 beta.</p>
  
  <p>I have some legacy code that actually relies on the VC 8 behavior, where we inherit from basic_fstream to add functionality:</p>
  
  <pre><code>class myFile : public basic_fstream&lt;char&gt; {
      public:
      void myWrite(const char* data, std::streamsize len) {
         write(data, len);
         // update some state variables (checksum, etc)
      }
  };
  </code></pre>
  
  <p>There are cases where it is beneficial to inspect the additional state without incurring the disk I/O (e.g. test writes).</p>
  
  <p>I'm assuming this is undefined behavior, and I'm lucky it doesn't crash in VC 8.  That said, I've had enough issues evaluating VS 2010 beta that I'd like to be sure.  Can anyone out there say definitively?</p>
  
  <p>EDIT: Call stack in VS 2010:</p>
  
  <pre><code>ostream::write
  ostream::sentry ctor
  istream::_Sentry_base ctor
  fstream::_Lock
  _file.c::_lock_file
  crashes on EnterCriticalSection( &amp;(((_FILEX *)pf)-&gt;lock) ), pf is null
  </code></pre>
  
  <p>Call stack on VS 2005:</p>
  
  <pre><code>ostream::write
  ostream::sentry ctor
  ostream::_Sentry_base ctor // different
  streambuf::_Lock
  _Mutex::_Lock()
  _Mtxlock in xmtx.c
  EnterCriticalSection(_Mtx), where _Mtx is valid
  </code></pre>
  
  <p>Also, compiles and runs with no errors with gcc-4.3.3 on Ubuntu.</p>
  
  <p>*** EDIT:</p>
  
  <p>After more digging, it appears that this in fact is a bug in Visual Studio 2010 Beta 1.</p>
  
  <p><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=456890" rel="nofollow noreferrer">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=456890</a></p>
  
  <p>According to this report, it has been fixed for the official release.</p>
  
  <p>Thanks for all of your input.</p>