Once a file has been closed, its corresponding FILE* typed variable becomes invalid and the stream may no longer be accessed through
this variable. In particular, a pointer to a FILE object may not be passed to fclose more than once.
Using the value of a pointer to a FILE object after the associated file is closed results in undefined behavior.
#include <stdio.h>
#include <stdlib.h>
int process_file(int print) {
FILE *f = fopen("example.txt", "r");
if (!f) {
perror("fopen() failed");
return 1;
}
if (print) {
char buffer[256];
while (fgets(buffer, 256, f)) {
printf("%s", buffer);
}
fclose(f);
}
// Further processing ...
fclose(f); // Noncompliant: file associated with `f` might already be closed.
return 0;
}
What is the potential impact?
If a pointer to a FILE object is used after the associated file is closed, the behavior of the application is undefined.
When a program comprises undefined behavior, the compiler no longer needs to adhere to the language standard, and the program has no meaning
assigned to it. The application might just crash, but in the worst case, the application may appear to execute correctly, while losing data or
producing incorrect results.