Home > Net >  What happens if I send a null pointer to fclose()?
What happens if I send a null pointer to fclose()?

Time:12-05

For example:

FILE* file_name;
file_name = fopen("some.txt", "r");  // some.txt isn't exist
if (file_name !=NULL)
  printf("nice");
fclose(file_name);

What happens in fclose?

CodePudding user response:

Passing a NULL pointer to fclose triggers undefined behavior.

The fclose function is documented as a library function in section 7.21.5.1 of the C standard, and section 7.1.4p1 states the following regarding library functions:

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.

Section 7.21.5.1 makes no explicit mention of a NULL pointer being passed to fclose, so the above statement applies.

CodePudding user response:

The C standard does not define the behavior.1 Some implementations may test the passed pointer and disregard a null pointer and may return success or may return failure. Other implementations may crash. You should not do this without a special purpose such as aiding diagnosis of a bug or investigating how it affects program vulnerabilities.

Footnote

1 The behavior is undefined becaue the specification for fclose in C 2018 7.21.5.1 specifies what fclose does when passed a pointer to a stream and does not specify what it does when passed a null pointer, and 7.1.4 1 says “… If an argument to a [standard library] function has an invalid value (such as… a null pointer…)…, the behavior is undefined.”

  •  Tags:  
  • c
  • Related