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

Compare with Current View Page History

« Previous Version 3 Next »

Narrower primitive types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integers represent exact values, floating-point numbers have limited precision. C99 says, in Section 6.3.1.4: "Real floating and integer"

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.

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.

#include <stdio.h>

int main() {
  int big = 1234567890;
  float approx = big;
  printf("%d\n", (big - (int)approx));
  return 0;
}

When compiled with GCC 4.3.2 on Linux, this program prints the value -46.

Compliant Solution

This solution replaces the float with a double. Furthermore, it uses a static assertion (see DCL03-C. Use a static assertion to test the value of a constant expression) to guarantee that the double type can represent any int without loss of precision.

#include <stdio.h>
#include <float.h>

/* define or include a definition of static_assert */

static_assert(sizeof(int) * 8 <= DBL_MANT_DIG); // 8 = bits / char

int main() {
  int big = 1234567890;
  double approx = big;
  printf("%d\n", (big - (int)approx));
  return 0;
}

On the same platform, this program prints 0.

Risk Assessment

Casting numeric types to floating-point types may lose information.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP36-C

low

unlikely

medium

P2

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 FLP36-CPP. Beware of precision loss when converting integral types to floating point.

This rule appears in the Java Secure Coding Standard as INT33-J. Be careful while casting numeric types to wider floating-point types.

References

[[ISO/IEC 9899:1999]] 6.3.1.4: "Real floating and integer"


INT32-J. Perform conversion from BigInteger to String and back properly      04. Integers (INT)      INT34-J. Perform explicit range checking to ensure integer operations do not overflow

  • No labels