Narrower primitive types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integers integer types represent exact values, floating-point numbers point types have limited precision. Subclause 6.3.1.4 paragraph 2 of the C Standard [ISO/IEC 9899:2011] states:
...
Conversion from integral types to floating-point types without sufficient precision can lead to loss of precision (loss of least significant bits). No runtime exception occurs despite the loss.
Noncompliant Code Example
In this noncompliant example, an int
is converted to float
:
...
When compiled with GCC 4.8.1 on Linux, this program prints the value -46
.
Compliant Solution
This solution replaces the float
with a double
. Furthermore, it uses a static assertion to guarantee that the double
type can represent any int
without loss of precision. (See DCL03-C. Use a static assertion to test the value of a constant expression.)
...
On the same platform, this program prints 0
.
Risk Assessment
Casting numeric types to floating-point types can lose information.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FLP36-C | Low | Unlikely | Medium | P2 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Bibliography
[ISO/IEC 9899:2011] | Subclause 6.3.1.4, "Real Floating and Integer" |
...