Main Content

MISRA C:2012 Rule 22.6

The value of a pointer to a FILE shall not be used after the associated stream has been closed

Description

Rule Definition

The value of a pointer to a FILE shall not be used after the associated stream has been closed1 .

Rationale

The CStandard states that the value of a FILE* pointer is indeterminate after you close the stream associated with it. Using a FILE* pointer after closing the file stream is undefined behavior.

Polyspace Implementation

Polyspace® reports a violation when you access a pointer to a FILE after closing the stream. If you access the closed file stream multiple times, Polyspace reports violation on the first use.

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 <stdio.h>

void func(void) {
    FILE *fp;
    void *ptr;

    fp = fopen("tmp","w");
    if(fp != NULL) {
        fclose(fp);
        fprintf(fp,"text"); // Non-compliant
    }
}

In this example, the stream associated with the FILE* pointer fp is closed with the fclose function. The rule is violated FILE* pointer fp is used before the stream is reopened.

Check Information

Group: Resources
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2015b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.