Search code examples
c++clanguage-lawyernull-pointer

Is NULL a valid FILE*?


I would like to have a function along the lines of

/*In header*/
void foo(FILE *outpt=stdout);

/*In implementation*/
void foo(FILE *outpt)
{
    if(outpt) fprintf(outpt, "Hello!");
}

But this code is (obviously) broken if NULL==stdout. (Edit: Jonathan Leffler points out that this code is already broken, because C has no default arguments. My C++ is showing, but the idea remains.)

C specifies that stdin, stdout, and stderr are implementation-defined FILE* constants, but I can't find a reference indicating that these constants are not NULL. Moreover, I can't find anything suggesting that NULL might not be a valid open file!

In MSVS, fprintf(NULL, "Hello!") calls abort(), suggesting that NULL is indeed an invalid FILE* specification.

C++ seems to follow C in this regard. I'm ultimately a C++ programmer, but I'll take a C answer, because it then likely carries over to C++ for backwards compatibility. So: does a C or C++ specification (including C2x and C++20) guarantee that NULL is an invalid FILE* specification?


Solution

  • C11 7.21.1/3 describes the standard file handles thusly:

    The macros are […]

    stderr
    stdin
    stdout

    which are expressions of type "pointer to FILE" that point to the FILE objects associated, respectively, with the standard error, input, and output streams.

    They would not point to any such objects if their values were null.