Main Content

CWE Rule 1341

Multiple Releases of Same Resource or Handle

Since R2023a

Description

Rule Description

The product attempts to close or release a resource or handle more than once, without any successful open between the close operations.

Polyspace Implementation

The rule checker checks for Closing previously closed resource.

Examples

expand all

Issue

This issue 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.

Example — Closing Previously Closed Resource
#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); //Noncompliant
}

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);
    }
}

Check Information

Category: Others

Version History

Introduced in R2023a