Main Content

ISO/IEC TS 17961 [chreof]

Using character values that are indistinguishable from EOF

Description

Rule Definition

Using character values that are indistinguishable from EOF.1

Polyspace Implementation

This checker checks for Character value absorbed into EOF.

Examples

expand all

Issue

Character value absorbed into EOF occurs when you perform a data type conversion that makes a valid character value indistinguishable from EOF (End-of-File). Bug Finder flags the defect in one of the following situations:

  • End-of-File: You perform a data type conversion such as from int to char that converts a non-EOF character value into EOF.

    char ch = (char)getchar();
    You then compare the result with EOF.
    if((int)ch == EOF){//...}
    The conversion can be explicit or implicit.

  • Wide End-of-File: You perform a data type conversion that can convert a non-WEOF wide character value into WEOF, and then compare the result with WEOF.

Risk

The data type char cannot hold the value EOF that indicates the end of a file. Functions such as getchar have return type int to accommodate EOF. If you convert from int to char, the values UCHAR_MAX (a valid character value) and EOF get converted to the same value -1 and become indistinguishable from each other. When you compare the result of this conversion with EOF, the comparison can lead to false detection of EOF. This rationale also applies to wide character values and WEOF.

Fix

Perform the comparison with EOF or WEOF before conversion.

Example - Return Value of getchar Converted to char
#include <stdio.h>
#include <stdlib.h>
#define fatal_error() abort()

char func(void)
{
    char ch;
    ch = getchar();
    if (EOF == (int)ch) {
        fatal_error();
    }
    return ch;
}

In this example, the return value of getchar is implicitly converted to char. If getchar returns UCHAR_MAX, it is converted to -1, which is indistinguishable from EOF. When you compare with EOF later, it can lead to a false positive.

Correction — Perform Comparison with EOF Before Conversion

One possible correction is to first perform the comparison with EOF, and then convert from int to char.

#include <stdio.h>
#include <stdlib.h>
#define fatal_error() abort()

char func(void)
{
    int i;               
    i = getchar();       
    if (EOF == i) {      
        fatal_error();
    }
    else {
        return (char)i;
    }
}

Check Information

Decidability: Undecidable

Version History

Introduced in R2019a


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.