CXX.CAST.SIGNED_CHAR_TO_INTEGER

The CXX.CAST.SIGNED_CHAR_TO_INTEGER checker flags cases where a signed char is assigned or converted to a larger signed integer type.

Vulnerability and risk

Unexpected results including negative values.

Mitigation and prevention

Always cast a signed char to an unsigned char before converting to a larger integer size.

Vulnerable code example

Copy
  void fun()
  {
      char *c_str="Welcome";
      unsigned char u_ch='K';
      int c;
      char ch = 'A';
 
      long var = ch;
 
     c = *c_str++;

     c = ch;

     if (c == *c_str);

     if (ch <= c);
 }

In this noncompliant example, Klocwork reports a CXX.CAST.SIGNED_CHAR_TO_INTEGER defect on lines 8, 10, 12, 14, and 16 because a signed char is being converted/assigned to a long integer type.

Fixed code example

Copy
  void fun()
   {
      char *c_str="Welcome";
      unsigned char u_ch='K';
      int c;
      char ch = 'A';

      c = *c_str++;
 
     c = (unsigned char)*c_str++;

     c = u_ch;
 }

In this fixed example, the char is cast to an unsigned char before it is converted to a larger integer size.