Main Content

Closing previously closed resource

Function closes a previously closed stream

Description

This defect occurs when a function attempts to close a stream that was closed earlier in your code and not reopened later.

Risk

The standard states that the value of a FILE* pointer is indeterminate after you close the stream associated with it. Performing the close operation on the FILE* pointer again can cause unwanted behavior.

Fix

Remove the redundant close operation.

Examples

expand all

#include <stdio.h>

void func(char* data) {
    FILE* fp = fopen("file.txt", "w");
    if(fp!=NULL) {
        if(data)
            fputc(*data,fp);
        else
            fclose(fp);
    }
    fclose(fp);
}

In this example, if fp is not NULL and data is NULL, the fclose operation occurs on fp twice in succession.

Correction — Remove Close Operation

One possible correction is to remove the last fclose operation. To avoid a resource leak, you must also place an fclose operation in the if(data) block.

#include <stdio.h>

void func(char* data) {
    FILE* fp = fopen("file.txt", "w");
    if(fp!=NULL) {
        if(data) {
            fputc(*data,fp);
            fclose(fp);
        }
        else
            fclose(fp);
    }
}

Result Information

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

Version History

Introduced in R2015b