Skip to main content

IAR Embedded Workbench for RL78 5.20

CERT-FIO42-C_a

In this section:
Synopsis

Close files when they are no longer needed.

Enabled by default

Yes

Severity/Certainty

Medium/Low

mediumlow.png
Full description

A call to the fopen() or freopen() function must be matched with a call to fclose() before the lifetime of the last pointer that stores the return value of the call has ended or before normal program termination, whichever occurs first. This check is identical to MISRAC2012-Dir-4.13_c, MISRAC2012-Rule-22.1_b, RESOURCE-file-no-close-all, SEC-FILEOP-open-no-close.

Coding standards
CERT FIO42-C

Ensure files are properly closed when they are no longer needed

MISRA C:2012 Dir-4.13

(Advisory) Functions which are designed to provide operations on a resource should be called in an appropriate sequence

MISRA C:2012 Rule-22.1

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

Code examples

The following code example fails the check and will give a warning:

#include <stdio.h>

int func(const char *filename) {
    FILE *f = fopen(filename, "r");
    if (NULL == f) {
        return -1;
    }
    /* ... */
    return 0;
}

The following code example passes the check and will not give a warning about this issue:

#include <stdio.h>

int func(const char *filename) {
    FILE *f = fopen(filename, "r");
    if (NULL == f) {
        return -1;
    }
    /* ... */
    if (fclose(f) == EOF) {
        return -1;
    }
    return 0;
}