A function returns while a stream or directory it opened is still open

tx0/c:stream-not-closedrecommendedwarningreliability/resourcesdepth fastbug, cwe-775

What it finds

f = fopen(path, "r"); ... if (bad) return -1;: on some path the function returns while a stream it opened with fopen, fdopen or tmpfile, a pipe from popen or a directory from opendir is still open and held only by a local variable. The descriptor stays in use until the process ends, and data written to the stream may never reach the file.

``c FILE *f = fopen(path, "w"); if (f == NULL) return -1; if (fputs(text, f) < 0) return -1; // f stays open return fclose(f); ``

The rule follows each function on its paths as leak-on-early-return does; a stream is given away when it is stored, returned or passed to a function other than those of the C library that only read or write it.

From the rule's source, stream_not_closed.rs.

Example from the rule's tests
#include <stdio.h> int save(const char *path, const char *text){  FILE *f = fopen(path, "w");  if (f == NULL)    return -1;  if (fputs(text, f) < 0)    return -1;tx0 reports: this returns without closing the stream f  return fclose(f);} void peek(const char *path){  char line[80];  FILE *f = fopen(path, "r");  if (f)    fgets(line, sizeof line, f);}tx0 reports: the function ends without closing the stream f FILE *open_log(const char *path){  FILE *f = fopen(path, "a");  return f;} void keep(FILE **out, const char *path){  FILE *f = fopen(path, "r");  *out = 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 from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/c:stream-not-closed" = "warning"

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:stream-not-closed] reason="..."

tx0 explain tx0/c:stream-not-closed shows the same in the terminal. Found a false positive? Report it.