Main Content

Resource leak

File stream not closed before FILE pointer scope ends or pointer is reassigned

Description

This defect occurs when you open a file stream by using a FILE pointer but do not close it before:

  • The end of the pointer’s scope.

  • Assigning the pointer to another stream.

Risk

If you do not release file handles explicitly as soon as possible, a failure can occur due to exhaustion of resources.

Fix

Close a FILE pointer before the end of its scope, or before you assign the pointer to another stream.

Examples

expand all

#include <stdio.h>

void func1( void ) {
    FILE *fp1;
    fp1 = fopen ( "data1.txt", "w" );
    fprintf ( fp1, "*" );

    fp1 = fopen ( "data2.txt", "w" );
    fprintf ( fp1, "!" );
    fclose ( fp1 );
}

In this example, the file pointer fp1 is pointing to a file data1.txt. Before fp1 is explicitly dissociated from the file stream of data1.txt, it is used to access another file data2.txt.

Correction — Release FILE Pointer

One possible correction is to explicitly dissociate fp1 from the file stream of data1.txt.

#include <stdio.h>

void func1( void ) {
    FILE *fp1;
    fp1 = fopen ( "data1.txt", "w" );
    fprintf ( fp1, "*" );
    fclose(fp1);

    fp1 = fopen ( "data2.txt", "w" );                  
    fprintf ( fp1, "!" );
    fclose ( fp1 );
}

Result Information

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

Version History

Introduced in R2015b

expand all