The char
type is the only unsigned primitive type in Java. It is easy to overlook this fact and assume that a signed value can be stored and retrieved successfully. Common effects of the defective code include memory leaks and misrepresented data.
Noncompliant Code Example
This noncompliant example is from the sun.net.httpserver.ChunkedInputStream
class. The InputStream
class's read()
method returns a signed 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
instead of -1. The termination test is doomed to fail. [[Pugh 08]]
char c; while ((c=(char)in.read())!= -1) { ... }
Compliant Solution
Always use a signed type of sufficient size to store signed data. To be compliant, use an integer
type to check for EOF
while reading in data.
int c; while ((c=in.read())!= -1) { ... }
Risk Assessment
Trying to store signed data in an unsigned type can lead to misinterpretations about the actual value.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
INT35-J |
low |
unlikely |
low |
P3 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[API 06]] Class InputStream
[[JLS 05]] 4.2 Primitive Types and Values
[[Pugh 08]] "Waiting for the end"