Main Content

CWE Rule 772

Missing Release of Resource after Effective Lifetime

Since R2024a

Description

Rule Description

The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.

Polyspace Implementation

The rule checker checks for Resource leak.

Examples

expand all

Issue

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

Example — FILE Pointer Not Released Before End of Scope
#include <stdio.h>

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

    fp1 = fopen ( "data2.txt", "w" ); //Noncompliant
    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 );
}

Check Information

Category: Resource Management Errors

Version History

Introduced in R2024a