Search code examples
cioposixfopen

POSIX fopen(NULL,"r")


I wonder, if it is legimate to call fopen with NULL filename. If it is, It saves me 2 lines of code. On my GNU/Linux machine it works, but It have to be portable. I looked POSIX fopen, but it says nothing about this case. Is it undefined behavior?


Solution

  • From the C standard (from 1999):

    7.1.4 Use of library functions

    Clause 1:

    Each of the following statements applies unless explicitly stated otherwise
    in the detailed descriptions that follow: If an argument to a function has an
    invalid value (such as a value outside the domain of the function, or a
    pointer outside the address space of the program, or a null pointer, or a
    pointer to non-modifiable storage when the corresponding parameter is not
    const-qualified) or a type (after promotion) not expected by a function with
    variable number of arguments, the behavior is undefined.
    

    The description of fopen() in that same standard does not mention NULL or null pointer at all.

    So, per the C standard, passing NULL as filename string pointer to fopen() leads to unefined behavior.

    POSIX may extend the behavior, however.