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
Copy
#include <stdio.h>
void read_file(FILE *file) {
char c;
do {
c = fgetc(file);
} while(c != EOF);
}
Klocwork flags the attempt to compare char variable 'c' to the EOF return variable at line 6.
Fixed code example
Copy
#include <stdio.h>
void read_file(FILE *file) {
int c;
do {
c = fgetc(file);
} while(c != EOF);
}
In the fixed example, variable 'c' is correctly defined as an int type.