Skip to content

Latest commit

 

History

History
48 lines (38 loc) · 1.18 KB

File metadata and controls

48 lines (38 loc) · 1.18 KB

useClosedFile

Message: Used file that is not opened.
Category: Undefined Behaviour
Severity: Error
Language: C/C++

Description

A read, write, or positioning call is made on a FILE* after it's already been closed.

Motivation

Using a file handle after fclose() is undefined behaviour - the underlying resource is gone, so any further operation on it can't be relied on to do anything sensible.

How to fix

Before:

#include <cstdio>
void f() {
    FILE *f1 = fopen("a.txt", "r");
    if (!f1) return;
    fclose(f1);
    char buf[1];
    fread(buf, 1, 1, f1); // <- 'f1' is already closed
}

After:

#include <cstdio>
void f() {
    FILE *f1 = fopen("a.txt", "r");
    if (!f1) return;
    char buf[1];
    fread(buf, 1, 1, f1);
    fclose(f1);
}

Related checkers