Main Content

CWE Rule 675

Multiple Operations on Resource in Single-Operation Context

Since R2024a

Description

Rule Description

The product performs the same operation on a resource two or more times, when the operation should only be applied once.

Polyspace Implementation

The rule checker checks for Opening previously opened resource.

Examples

expand all

Issue

This issue occurs when a file handling function such as fopen opens a file that was previously opened and not closed subsequently.

Risk

If you open a resource multiple times, you can encounter:

  • A race condition when accessing the file.

  • Undefined or unexpected behavior for that file.

  • Portability issues when you run your program on different targets.

Fix

Once a resource is open, close the resource before reopening.

Example — File Reopened With New Permissions
#include <stdio.h>
const char* logfile = "my_file.log";

void doubleresourceopen()
{
    FILE* fpa = fopen(logfile, "w");
    if (fpa == NULL) {
        return;
    }
    (void)fprintf(fpa, "Writing");
    FILE* fpb = fopen(logfile, "r"); //Noncompliant
    (void)fclose(fpa);
    (void)fclose(fpb);
}

In this example, a logfile is opened in the first line of this function with write privileges. Halfway through the function, the logfile is opened again with read privileges.

Correction — Close Before Reopening

One possible correction is to close the file before reopening the file with different privileges.

#include <stdio.h>
const char* logfile = "my_file.log";

void doubleresourceopen()
{
    FILE* fpa = fopen(logfile, "w");
    if (fpa == NULL) {
        return;
    }
    (void)fprintf(fpa, "Writing");
    (void)fclose(fpa);
    FILE* fpb = fopen(logfile, "r");
    (void)fclose(fpb);
}

Check Information

Category: Others

Version History

Introduced in R2024a