You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

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 (Character.MAX_VALUE, decimal 65535) 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.

Other Languages

This rule appears in the C Secure Coding Standard as FIO34-C. Use int to capture the return value of character IO functions.

This rule appears in the C++ Secure Coding Standard as FIO34-CPP. Use int to capture the return value of character IO functions.

References

[[API 06]] Class InputStream
[[JLS 05]] 4.2 Primitive Types and Values
[[Pugh 08]] "Waiting for the end"

  • No labels