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.