lundi 29 juin 2015

std::iostream read or write with count zero and invalid buffer

The following code reads a file containing some value that represents the length of more following data.

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);

It fails with the MSVC 2013 compiler if dataLen = 0. It causes an abort with the message Expression: invalid null pointer, because data.data() returns a null pointer.

This question suggests that a count of 0 is valid for std::basic_istream::read, but the third comment on the question seems to point out my issue.

Is it valid C++ to pass an invalid pointer to std::basic_istream::read (or std::basic_ostream::write) with a size of 0? It would seem logical to me, because the call should not touch the buffer anyway.

The obvious solution is to deal with this special case with an if clause, but I am wondering if MSVC is wrong once again.

Here is a compiled example of clang running the program fine: http://ift.tt/1FKD7lm

Aucun commentaire:

Enregistrer un commentaire