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 1

1  void fun()
2  {
3      char *c_str="Welcome";
4      unsigned char u_ch='K';
5      int c;
6      char ch = 'A';
7 
8      long var = ch;
9 
10     c = *c_str++;
11
12     c = ch;
13
14     if (c == *c_str);
15
16     if (ch <= c);
17 }

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 1

1  void fun()
2   {
3      char *c_str="Welcome";
4      unsigned char u_ch='K';
5      int c;
6      char ch = 'A';
7 
8      c = *c_str++;
9 
10     c = (unsigned char)*c_str++;
11
12     c = u_ch;
13 }

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