Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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


1   static unsigned char* reference = "Polisen förstärker i Malmö";

2   int foo(char* str)
3   {
4     unsigned char* rptr;

5       for( rptr = reference; *ptr && *str; str++, rptr++ )
6           if( *str != *rptr )
7               return 0;
8       return 1;
9   }

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

Fixed code example


1   #define BYTE unsigned char

2   static BYTE* reference = "Polisen förstärker i Malmö";

3   int foo(BYTE* str)
4   {
5     BYTE* rptr;

6       for( rptr = reference; *ptr && *str; str++, rptr++ )
7           if( *str != *rptr )
8               return 0;
9   }

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