C99 C defines <
, >
, <=
, and >=
to be relational operators, and it defines ==
and !=
to be equality operators..
If a for
or while
statement uses a loop counter, than it is safer to use a relational operator (such as <
) to terminate the loop than using to use an equality operator (such as !=
).
...
This noncompliant code example appears to have 5 have five iterations, but , in fact, the loop never terminates.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t i;
for (i = 1; i != 10; i += 2) {
/* ... */
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
size_t i;
for (i = 1; i <= 10; i += 2 ) {
/* ... */
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t begin, size_t end) {
size_t i;
for (i = begin; i != end; ++i) {
/* ... */
}
}
|
...
Again, using a relational operator instead of equivalence guarantees loop termination. If begin >= end
, the loop never executes its body.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t begin, size_t end) {
size_t i;
for (i = begin; i < end; ++i) {
/* ... */
}
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t begin, size_t step) {
size_t i;
for (i = begin; i <= SIZE_MAX; i += step) {
/* ... */
}
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t begin, size_t step) {
if (0 < step) {
int i;
for (i = begin; i <= INT_MAX - step; i += step) {
/* ... */
}
}
}
|
...
MSC21-EX1: If the loop counter is incremented by one by 1 on each iteration, and it is known that the starting value of a loop is less than or equal to the ending value, then an equality operator may be used to terminate the loop. Likewise, if the loop counter is decremented by one by 1 on each iteration, and it is known that the starting value of the loop is greater than or equal to the ending value, then an equality operator may be used to terminate the loop.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t i;
for (i = 1; i != 5; ++i) {
/* ... */
}
|
...
Testing for exact values runs the risk of a loop terminating much longer than expected , or never terminating at all.
...
Tool | Version | Checker | Description | section|
---|---|---|---|---|
ROSE |
|
|
|
Related Vulnerabilities
...
The CERT Oracle Secure Coding Standard for Java: MSC57-J. Use inequality operators to terminate loops whose counter changes by more than one
...
Sources
ISO/IEC 9899:1999 Section 2011 Section 6.5.8, "Relational operators," and Section 6.5.9, "Equality operators"
...