A stream or directory is closed twice

tx0/c:double-closedefaultwarningreliability/api-misusedepth fastbug, cwe-1341

What it finds

fclose(f); and later fclose(f); again on some path: the second call closes a stream that no longer exists, which is undefined and may close a stream opened since in its place. The same holds for pclose and closedir.

``c fclose(out); if (failed) { fclose(out); // closed above return -1; } ``

The rule follows each function on its paths as double-free does.

From the rule's source, double_close.rs.

Example from the rule's tests
#include <stdio.h>#include <dirent.h> int save(const char *path, const char *text, int fail){  FILE *f = fopen(path, "w");  if (f == NULL)    return -1;  fputs(text, f);  fclose(f);  if (fail) {    fclose(f);tx0 reports: f is closed a second time with fclose    return -1;  }  return 0;} void list(const char *path){  DIR *d = opendir(path);  if (!d)    return;  closedir(d);  closedir(d);tx0 reports: d is closed a second time with closedir} void reopened(const char *path){  FILE *f = fopen(path, "r");  if (!f)    return;  fclose(f);  f = fopen(path, "r");  if (f)    fclose(f);}
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:double-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:double-close] reason="..."

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