Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Because floating-point numbers can represent fractions, it is programmers often mistakenly assumed assume that they can represent any simple fraction exactly. In fact, floating-point numbers are subject to precision limitations just as integers are. Further, and binary floating-point numbers cannot represent all decimal fractions exactly, even if when the fractions can be represented in a small number of decimal digits.

In addition, because floating-point numbers can represent large values, it is programmers often mistakenly assumed assume that they can represent all digits of those values. To gain a large dynamic range, floating-point numbers maintain a fixed number of bits of precision and an exponent. Incrementing a large floating-point value may not change that value within the available precision. Consequently, floating-point variables should not be used as loop counters.

...

This compliant solution uses an integer loop counter from which the desired floating-point value is derived.

...

Code Block
bgColor#FFCCCC
for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) {
  /* ... */
}

This produces an infinite loopThe code loops forever on execution.

Compliant Solution

This compliant solution uses an integer loop counter from which the floating-point value is derived. Additionally, it uses a double is used instead of a float to gain enough precision so that the available precision suffices to represent the desired values.

Code Block
bgColor#ccccff
for (int count = 1; count <= 10; count += 1) {
  double x = 100000000.0 + count;
  /* ... */
}

...

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

FLP07-J

low

probable

low

P6

L2

Automated Detection

TODOAutomated detection of floating-point loop counters is straightforward.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

...

This guideline appears in the C++ Secure Coding Standard as FLP30-CPP. Do not use floating point variables as loop counters.

Bibliography

Wiki Markup
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 34: Down for the Count
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 4.2.3, Floating-Point Types, Formats, and Values|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3]
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 34: Down for the Count

...

FLP06-J. Check floating point inputs for exceptional values      07. Floating Point (FLP)      FLP08-J. Avoid using floating point literals with the BigDecimal constructor