Narrower primitive arithmetic types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integer types represent exact values, floating-point types have limited precision. Subclause 6The C Standard, 6.3.1.4 paragraph 2 of the C Standard [ISO/IEC 9899:2011], states:
When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined. Results of some implicit conversions may be represented in greater range and precision than that required by the new type (see 6.3.1.8 and 6.8.6.4).
...
In this noncompliant example, a large value of type long int
is converted to a value of type float
without ensuring it is representable in the type:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> int main(void) { long int big = 1234567890; float approx = big; printf("%d\n", (big - (long int)approx)); return 0; } |
When compiled with GCC 4.8.1 on LinuxFor most floating-point hardware, the value closest to 1234567890
that is representable in type float
is 1234567844
; consequently, this program prints the value -46
.
...
This compliant solution replaces the type float
with a double
. Furthermore, it uses an assertion to guarantee that the double
type can represent any long int
without loss of precision for implementations. (See see INT35-C. Use correct integer precisions for the definition and rationale of the PRECISION()
macro and MSC11-C. Incorporate diagnostic tests using assertions):
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> #include <stdio.h> #include <float.h> #include <limits.h> extern size_t popcount(uintmax_t); /* See INT35-C */ #define PRECISION(umax_value) popcount(umax_value) int main(void) { assert(PRECISION(INTLONG_MAX) <= DBL_MANT_DIG * log2(DBL_MANT_DIG)); long int big = 1234567890; double approx = big; printf("%d\n", (big - (long int)approx)); return 0; } |
On the same platformimplementation, this program prints 0
, implying that the integer value 1234567890
is representable in type double
without change.
Risk Assessment
Conversion from integral types to floating-point types without sufficient precision can lead to loss of precision (loss of least significant bits).
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Bibliography
[ISO/IEC 9899:2011] | Subclause 66.3.1.4, "Real Floating and Integer" |
...