Main Content

MISRA C:2012 Rule 22.1

All resources obtained dynamically by means of Standard Library functions shall be explicitly released

Description

Rule Definition

All resources obtained dynamically by means of Standard Library functions shall be explicitly released.

Rationale

Resources are something that you must return to the system once you have used them. Examples include dynamically allocated memory and file descriptors.

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

Polyspace Implementation

The checker flags uses of:

  • Memory-allocation functions such as malloc and aligned_alloc if the memory is not released.

  • File opening functions such as fopen if the file is not closed.

You can check for this rule with a Bug Finder analysis only.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<stdlib.h>

void performOperation(int);

int func1(int num)
{
    int* arr1 = (int*) malloc(num * sizeof(int));

    return 0; /* Non-compliant - memory allocated to arr1 is not released */
}

int func2(int num)
{
    int* arr2 = (int*) malloc(num * sizeof(int));

    free(arr2);
    return 0; /* Compliant - memory allocated to arr2 is released */
}

In this example, the rule is violated when memory dynamically allocated using the malloc function is not freed using the free function before the end of scope.

#include <stdio.h>
void func1( void ) {
    FILE *fp1;
    fp1 = fopen ( "data1.txt", "w" );
    fprintf ( fp1, "*" );

    fp1 = fopen ( "data2.txt", "w" );              /* Non-compliant */
    fprintf ( fp1, "!" );
    fclose ( fp1 );
}

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

    fp2 = fopen ( "data2.txt", "w" );              /* Compliant */
    fprintf ( fp2, "!" );
    fclose ( fp2 );
}

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. Therefore, the rule 22.1 is violated.

The rule is not violated in func2 because file data1.txt is closed and the file pointer fp2 is explicitly dissociated from data1.txt before it is reused.

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2015b