The char
type is the only unsigned primitive type in Java. It is easy to overlook this fact and assume that As a result, a signed value can cannot be stored and retrieved successfully . Common effects of the defective code include memory leaks and misrepresented data.
Noncompliant Code Example
from a variable of type char
.
Wiki Markup |
---|
This noncompliant example is from the {{sun.net.httpserver.ChunkedInputStream}} class. The {{InputStream}} class'sIn particular, comparing a value of type {{char}} with -1 will never yield {{true}}. However, because the method {{read()}} method returns a-1 signedto byte in the form of a signed integer. In this case, the end of stream is being checked by casting the return value to a {{char}}. This conversion would leave the value of {{c}} as {{0xffff}} ({{Character.MAX_VALUE}}, decimal 65535) instead ofindicate {{EOF}}, it is tempting to try to compare the character returned by {{read()}} with -1. The terminationThis test is doomeda tocommon fail.error \[[Pugh 08|AA. Java References#Pugh 08]\] . |
Noncompliant Code Example
In this noncompliant code, the int
returned by the read()
method is cast directly to a char
, and that is compared with -1 to try to detect EOF
. This test never evaluates to true
.
Code Block | ||
---|---|---|
| ||
char c; while ((c=(char)in.read())!= -1) { ... } |
...
Always use a signed type of sufficient size to store signed data. To be compliant, use an integer
int
type to check for EOF
while reading in data. If the int
value returned by read()
is not -1, then it can be safely cast to a char
.
Code Block | ||
---|---|---|
| ||
int c; while ((c=in.read())!= -1) {ch = (char)c; ... } |
Risk Assessment
Trying to store Storing signed data in an a variable of the unsigned type char
can lead to misinterpretations about the actual valuemisinterpreted data and possibly to memory leaks. Furthermore, comparing a value of type char
with -1 never evaluates to true
. This error could lead to a denial of service attack.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT35-J | low | unlikely | low | P3 | L3 |
...