Main Content

Use of previously closed resource

Function operates on a previously closed stream

Description

This defect occurs when a function operates on a stream that you closed earlier in your code.

Risk

The standard states that the value of a FILE* pointer is indeterminate after you close the stream associated with it. Operations using the FILE* pointer can produce unintended results.

Fix

One possible fix is to close the stream only at the end of operations. Another fix is to reopen the stream before using it again.

Examples

expand all

#include <stdio.h>

void func(void) {
    FILE *fp;
    void *ptr;

    fp = fopen("tmp","w");
    if(fp != NULL) {
        fclose(fp);
        fprintf(fp,"text");
    }
}

In this example, fclose closes the stream associated with fp. When you use fprintf on fp after fclose, the Use of previously closed resource defect appears.

Correction — Close Stream After All Operations

One possible correction is to reverse the order of the fprintf and fclose operations.

#include <stdio.h>

void func(void) {
    FILE *fp;
    void *ptr;

    fp = fopen("tmp","w");
    if(fp != NULL) {
        fprintf(fp,"text");
        fclose(fp);
    }
}

Result Information

Group: Resource management
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: CLOSED_RESOURCE_USE
Impact: High

Version History

Introduced in R2015b