Writing to default built fstream: Undefined Behavior?

Consider the following:

std::basic_fstream<char> testfile;
testfile.write(reinterpret_cast<const char*>(&someInt), sizeof(int));
testfile.close();

      

This works without complaint when building with VC 8.0, but crashes when building with VC 10.0 beta.

I have some old code that really relies on VC 8 behavior, where we inherit basic_fstream to add functionality:

class myFile : public basic_fstream<char> {
    public:
    void myWrite(const char* data, std::streamsize len) {
       write(data, len);
       // update some state variables (checksum, etc)
    }
};

      

There are times when it is useful to check for additional state without causing disk I / O (such as writing a test).

I'm assuming this behavior is undefined and I'm lucky it doesn't crash in VC 8. However, I've had enough trouble evaluating the VS 2010 beta that I would like to be sure about. Can anyone say definitively?

EDIT: Call stack in VS 2010:

ostream::write
ostream::sentry ctor
istream::_Sentry_base ctor
fstream::_Lock
_file.c::_lock_file
crashes on EnterCriticalSection( &(((_FILEX *)pf)->lock) ), pf is null

      

Call stack on VS 2005:

ostream::write
ostream::sentry ctor
ostream::_Sentry_base ctor // different
streambuf::_Lock
_Mutex::_Lock()
_Mtxlock in xmtx.c
EnterCriticalSection(_Mtx), where _Mtx is valid

      

Also compiles and runs without error with gcc-4.3.3 on Ubuntu.

*** EDIT:

After more digging, it looks like this is actually a bug in Visual Studio 2010 Beta 1.

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=456890

According to this report, it has been fixed for official release.

Thanks for all your data.

+2


source to share


1 answer


Have you checked to see if exceptions are resolved when thread state is set to fail or unsuccessful? Since the C ++ standard says the following abt 'write' methdod: -

27.6.2.7. Unformatted output functions

Point: -5

basic_ostream& write(const char_type* s, streamsize n);

Effects: behaves like unformatted output (as described in 27.6.2.7, clause 1). After the creation of the watchdog object, characters are obtained for insertion from consecutive locations in the array, whose first element is denoted by s. Characters are inserted as long as the following occurs:



  • Are inserted
  • n characters;
  • the insert in the output sequence fails (in which case the function calls setstate badbit), which may call ios_base :: failure (27.4.4.3)).

This means that no more testfile.fail()

returns true. Ideally, this shouldn't be a disaster. I suspect the exception is being thrown and not caught (but maybe I am completely wrong).

+2


source







All Articles