2

Consider the following:

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

This runs with no complaint when built with VC 8.0, but crashes when built with VC 10.0 beta.

I have some legacy code that actually relies on the VC 8 behavior, where we inherit from 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 cases where it is beneficial to inspect the additional state without incurring the disk I/O (e.g. test writes).

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?

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 with no errors with gcc-4.3.3 on Ubuntu.

*** EDIT:

After more digging, it appears that this in fact is 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 the official release.

Thanks for all of your input.

4

1 回答 1

2

您是否检查过当流状态设置为失败或错误时是否启用了抛出异常?因为 C++ 标准说以下 abt 'write' 方法:-

27.6.2.7。未格式化的输出函数

点数:-5

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

效果:表现为未格式化的输出函数(如 27.6.2.7 第 1 段所述)。构造哨兵对象后,从数组的连续位置获取要插入的字符,该数组的第一个元素由 s 指定。插入字符直到出现以下任一情况:

  • 插入 n 个字符;
  • 在输出序列中插入失败(在这种情况下,函数调用 setstate badbit),这可能会抛出 ios_base::failure (27.4.4.3))。

这意味着最多testfile.fail()返回true。理想情况下它不应该崩溃。我怀疑一个异常被抛出并且没有被捕获(但也许我完全错了)。

于 2009-09-02T05:55:40.817 回答