Main Content

MISRA C:2012 Rule 22.7

The macro EOF shall only be compared with the unmodified return value from any Standard Library function capable of returning EOF

Description

Rule Definition

The macro EOF shall only be compared with the unmodified return value from any Standard Library function capable of returning EOF.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

The EOF value returned by a standard library function can become indistinguishable from a valid character code if the value returned is converted to another type. In such cases, testing the converted value against EOF does not reliably determine whether the end of the file has been reached or if an error has occurred.

To determine the end of file reliably, use the functions feof() or ferror().

Polyspace Implementation

Polyspace® reports a violation of this rule if these events happen in a sequence:

  • A standard library function that can return EOF is called.

  • The return value of the function is then converted to a different type. This conversion can happen over several steps.

  • The converted return value is then compared to the macro EOF.

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>
#include <stdint.h>

void f1(void)
{
    char ch;
    ch = (char) getchar();
    if (EOF != (int32_t) ch) {    /* Noncompliant */
    }
}

void f2(void)
{
    char ch;
    ch = (char) getchar();
    if (!feof(stdin)) {           /* Compliant */
    }
}

void f3(void)
{
    int32_t i_ch;
    i_ch = getchar();
    if (EOF != i_ch) {            /* Compliant */
        char ch;
        ch = (char) i_ch;
    }
}

In this example:

  • The test in the function f1() is noncompliant. It is not be reliable because the return value of getchar() is cast to a narrower type before checking for EOF.

  • The test in the function f2() is compliant. It uses feof() to check for EOF after the return value from getchar() has been subjected to type conversion.

  • The test in the function f3() is compliant. It is reliable because it uses the unconverted return value of getchar() when comparing to EOF.

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2017a