A stream or directory is used after it was closed

tx0/c:use-after-closedefaultwarningreliability/resourcesdepth fastbug, cwe-672

What it finds

fclose(f); and then fprintf(f, ...) or fgets(buf, n, f) on some path: the stream no longer exists, and using it is undefined. The same holds for a directory after closedir and a pipe after pclose.

``c fclose(log); if (verbose) fprintf(log, "done\n"); // log was closed above ``

The rule follows each function on its paths as use-after-free does. A use is a call of a function of the C library that reads or writes the stream, such as fprintf, fputs, fread, fflush or readdir.

From the rule's source, use_after_close.rs.

Example from the rule's tests
#include <stdio.h> void finish(FILE *log, int verbose){  fclose(log);  if (verbose)    fprintf(log, "done\n");tx0 reports: log is used after it was closed} void reopen(FILE *log, const char *path){  fclose(log);  log = fopen(path, "a");  if (log)    fputs("again\n", log);}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/c:use-after-close" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:use-after-close] reason="..."

tx0 explain tx0/c:use-after-close shows the same in the terminal. Found a false positive? Report it.