PORTING.UNSIGNEDCHAR.RELOP

Relational operations between signed/unsigned char and char without signedness specification

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.UNSIGNEDCHAR.RELOP checker detects situations in which a relational operation is used between an explicitly signed or unsigned char and a char without signedness specification.

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
   static unsigned char* reference = "Polisen förstärker i Malmö";
   int foo(char* str)
   {
     unsigned char* rptr;
       for( rptr = reference; *ptr && *str; str++, rptr++ )
           if( *str != *rptr )
               return 0;
       return 1;
   }

In this example, the incoming implicitly signed string is compared with a reference explicitly signed string, resulting in undefined behavior.

Fixed code example

Copy
   #define BYTE unsigned char
   static BYTE* reference = "Polisen förstärker i Malmö";
   int foo(BYTE* str)
   {
     BYTE* rptr;
       for( rptr = reference; *ptr && *str; str++, rptr++ )
           if( *str != *rptr )
               return 0;
   }

In the fixed example, using an abstract type specified in a #define allows us to be sure that comparisons are accurate.