Search code examples
posixsystem-callsc11

Do operations such as fwrite and fread have undefined behavior when stream is null?


I'm specifically looking for the word in the C11 standard (ISO/IEC 9899:2011), or a POSIX page. I checked the POSIX manual for fwrite out, but it doesn't mention undefined behavior at all. However, the manual for fclose does say that

After the call to fclose(), any use of stream results in undefined behavior.

But I still don't see whether a NULL stream causes UB.


Solution

  • Both fread() and fwrite() expect the stream argument to be a value returned by a successful call to fopen(), fdopen() or freopen(). Since those functions return NULL on error, the stream argument cannot be NULL.

    Since the manual page does not say what happens when stream is not a value returned by a successful call to fopen() etc. this means that the manual page does not say what happens when stream is not a value returned by a successful call to fopen() etc., or, in other words, the behavior is not defined.

    See also the accepted answer to the question "Why glibc's fclose(NULL) cause segmentation fault instead of returning error" on this board.