CertC-FIO46¶
Do not access a closed file
Required inputs: IR, StaticSemanticAnalysis
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:
#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.
#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 |
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" |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
possible_use_after_free |
Possibly access to a closed file |
None |
False |
use_after_free |
Do not access a closed file |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
functions_with_ignored_deallocators¶
functions_with_ignored_deallocators : set[str] = set()
maximum_number_of_threads¶
maximum_number_of_threads : int = 0
report_freed_this_at_call¶
report_freed_this_at_call : bool = False
report_read_pointer_args_in_calls_to_undefined¶
report_read_pointer_args_in_calls_to_undefined : bool = True
resources¶
resources : set[str] = {'FileHandle'}
witness_paths¶
witness_paths : bool = True