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.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

/* print a string replacing any non-ASCII characters with ? */
1   void safe_print(char *s) {
2     for (; *s; s++) {
3       if (*s < 128) {    /* PORTING.UNSIGNEDCHAR.OVERFLOW.TRUE */
4         putchar(*s);
5       } else {
6         putchar('?');
7       }
8     }
9   }

10  int main() {
11    safe_print("na\xEFve\n"); /* "naïve" in Latin-1 character set */
12    return 0;
13  }

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

Fixed code example

/* print a string replacing any non-ASCII characters with ? */
1   void safe_print(unsigned char *s) {
2     for (; *s; s++) {
3       if (*s < 128) {    
4         putchar(*s);
5       } else {
6         putchar('?');
7       }
8     }
9   }

10  int main() {
11    safe_print("na\xEFve\n"); /* "naïve" in Latin-1 character set */
12    return 0;
13  }

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