Main Content

Opening previously opened resource

Opening an already opened file

Description

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

Examples

expand all

#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");
    (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);
}

Result Information

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

Version History

Introduced in R2016b