Skip to main content
GitHub

FIO46-C. Do not access a closed file

Using the value of a pointer to a FILE object after the associated file is closed is undefined behavior . (See undefined behavior 153 .) Programs that close the standard streams (especially stdout but also stderr and stdin ) must be careful not to use these streams in subsequent function calls, particularly those that implicitly operate on them (such as printf() , perror() , and getc() ).

This rule can be generalized to other file representations.

Noncompliant Code Example

In this noncompliant code example, the stdout stream is used after it is closed:

Non-compliant code
#include <stdio.h>
 
int close_stdout(void) {
  if (fclose(stdout) == EOF) {
    return -1;
  }
 
  printf("stdout successfully closed.\n");
  return 0;
}

Compliant Solution

In this compliant solution, stdout is not used again after it is closed. This must remain true for the remainder of the program, or stdout must be assigned the address of an open file object.

Compliant code
#include <stdio.h>
 
int close_stdout(void) {
  if (fclose(stdout) == EOF) {
    return -1;
  }

  fputs("stdout successfully closed.", stderr);
  return 0;
}

Risk Assessment

Using the value of a pointer to a FILE object after the associated file is closed is undefined behavior 153 .

Rule Severity Likelihood Detectable Repairable Priority Level
FIO46-C Medium Unlikely No No P2 L3

Automated Detection

ToolVersionCheckerDescription
Astrée
25.10
Supported
CodeSonar
9.2p0
IO.UACUse after close
Compass/ROSE
Coverity
2017.07
USE_AFTER_FREEImplemented
Helix QAC
2025.2
DF2696, DF2697, DF2698
Klocwork
2025.2
SV.INCORRECT_RESOURCE_HANDLING.URH
LDRA tool suite
9.7.1
48 DPartially implemented
Parasoft C/C++test
2026.1
CERT_C-FIO46-aDo not use resources that have been freed
PC-lint Plus
1.4
2471Fully supported
Polyspace Bug Finder
R2025b
CERT C: Rule FIO46-CChecks for use of previously closed resource (rule partially covered)
SonarQube C/C++ Plugin
3.11
S3588

Search for vulnerabilities resulting from the violation of this rule on the CERT website .

Bibliography

[ IEEE Std 1003.1:2013 ]XSH, System Interfaces, open
[ ISO/IEC 9899:2024 ]

Subclause 7.23.3, "Files"
Subclause 7.23.5.1, "The fclose Function"