以下代码读取包含某个值的文件,该值代表更多后续数据的长度。std :: iostream使用计数零和无效缓冲区读取或写入
auto file = std::ifstream(filename, std::ios::in | std::ios::binary);
// dataLen = Read some header field containing a length of following data.
std::vector<unsigned char> data;
data.resize(dataLen);
file.read((char*)data.data(), dataLen);
如果使用了dataLen = 0
,则MSVC 2013编译器失败。它导致消息Expression: invalid null pointer
中止,因为data.data()
返回空指针。
This question表明0的count
对std::basic_istream::read
有效,但对问题的第三个评论似乎指出了我的问题。
是否有效C++将大小为0的无效指针传递给std::basic_istream::read
(或std::basic_ostream::write
)?对我来说这似乎合乎逻辑,因为呼叫不应触碰缓冲区。
显而易见的解决方案是用if子句处理这个特殊情况,但我想知道MSVC是否再次出错。
这里是正在运行的程序罚款铿锵的编译例子:http://coliru.stacked-crooked.com/a/c036ec31abd80f22
为了澄清,“这会导致与消息中止......” - 是由一个未捕获的异常* *触发?或者它是VS标准C++库的调试二进制文件中的runtime * assertion *。这似乎没有什么大的差别,但它是相关的。并且在*发布*版本中后面的行为是否相同? – WhozCraig
@WhozCraig它说'Debug Assertion Failed!'并且在发布版本中不会发生。 – typ1232
@ typ1232那么,为什么不在调试模式下只是做'data.resize(dataLen + 1)'? – Barry