Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

CWARN.CMPCHR.EOF

Char expression is compared with EOF constant

The CWARN.CMPCHR.EOF checker flags instances in which a char expression is compared with an EOF constant.

Vulnerability and risk

Functions for reading single characters from a file, such as getchar, fgetc and getc, normally return an int value to distinguish an EOF return value (0xffffffff on 32-bit platforms) from a read byte whose value equals -1 (0x000000ff). So it's typically a mistake when a variable of char type is compared with an EOF constant, and an int variable should be used instead.

Vulnerable code example

01 #include <stdio.h>
02 
03 void read_file(FILE *file) {
04   char c;
05   do {
06     c = fgetc(file);
07   } while(c != EOF);
08 }

Klocwork flags the attempt to compare char variable 'c' to the EOF return variable at line 6.

Fixed code example

01 #include <stdio.h>
02 
03 void read_file(FILE *file) {
04   int c;    
05   do {
06     c = fgetc(file);
07   } while(c != EOF);
08 }

In the fixed example, variable 'c' is correctly defined as an int type.