PORTING.UNSIGNEDCHAR.OVERFLOW.TRUE

Relational expression may be always true

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.UNSIGNEDCHAR.OVERFLOW.TRUE checker detects situations in which a relational expression may be always true, depending on 'char' type signedness.

Vulnerability and risk

The 'char' data type isn't precisely defined in the C standard, so an instance may or may not be considered to be signed. Some compilers allow the sign of 'char' to be switched using compiler options, but best practice is for developers to write unambiguous code at all times to avoid problems in porting code.

Mitigation and prevention

Always specify whether or not the 'char' type is signed. This is best done by a using a typedef or #define definition that is then rigorously used everywhere.

Vulnerable code example

Copy
/* print a string replacing any non-ASCII characters with ? */
   void safe_print(char *s) {
     for (; *s; s++) {
       if (*s < 128) {    /* PORTING.UNSIGNEDCHAR.OVERFLOW.TRUE */
         putchar(*s);
       } else {
         putchar('?');
       }
     }
   }
  int main() {
    safe_print("na\xEFve\n"); /* "naïve" in Latin-1 character set */
    return 0;
  }

The safe_print() would only work properly with unsigned char.

Fixed code example

Copy
/* print a string replacing any non-ASCII characters with ? */
   void safe_print(unsigned char *s) {
     for (; *s; s++) {
       if (*s < 128) {    
         putchar(*s);
       } else {
         putchar('?');
       }
     }
   }
  int main() {
    safe_print("na\xEFve\n"); /* "naïve" in Latin-1 character set */
    return 0;
  }

In the fixed example, char is changed to unsigned char in the declaration of the function parameter.