Search code examples
c++fwrite

Can passing a Nullpointer to fwrite cause problems


I've recently written some code where, under certain circumstances, a Nullpointer might be passed to fwrite.

Although it worked on windows I've wondered if it might cause problems on other platforms or if there's anything that prevents that.


How I produced such a mess ;) :

std::vector<unsigned char> bytes;

// ...
// bytes could be filled but may be empty.

const char* bytesToWrite = (const char*) bytes.data();   // .data() will return NULL if empty
unsigned long count = bytes.size();

if (count == fwrite(bytesToWrite, 1, count, handle)) //...

Solution

  • From the Microsoft documentation:

    fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined. If either stream or buffer is a null pointer, or if an odd number of bytes to be written is specified in Unicode mode, the function invokes the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, this function sets errno to EINVAL and returns 0.

    So it works in Windows (well, you get an explicit error instead of a loud crash but it's still not very useful). But there's no trace of this case in Unix/Linux so just don't rely on it. Always test beforehand:

    if (buffer != NULL) { fwrite(buffer, ...
    

    or use assert(buffer != NULL) to turn undefined behaviour into defined behaviour.