Main Content

CWE Rule 910

Use of Expired File Descriptor

Since R2023a

Description

Rule Description

The software uses or accesses a file descriptor after it has been closed.

Polyspace Implementation

The rule checker checks for Use of previously closed resource.

Examples

expand all

Issue

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

Example — Use of FILE* Pointer After Closing Stream
#include <stdio.h>

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

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

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

Check Information

Category: Resource Management Errors

Version History

Introduced in R2023a