Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSIX fopen(NULL,"r")

Tags:

c

io

posix

fopen

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?

like image 268
KAction Avatar asked Sep 27 '12 11:09

KAction


1 Answers

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.

like image 157
Alexey Frunze Avatar answered Sep 24 '22 02:09

Alexey Frunze