Main Content

Hard-coded loop boundary

Loop boundary is a numerical value instead of symbolic constant

Description

This defect occurs when you use a numerical value instead of symbolic constant for the boundary of a for, while or do-while loop.

Risk

Hard-coded loop boundary causes the following issues:

  • Hard-coded loop boundary makes the code vulnerable to denial of service attacks when the loop involves time-consuming computation or resource allocation.

  • Hard-coded loop boundary increases the likelihood of mistakes and maintenance costs. If a policy change requires developers to change the loop boundary, they must change every occurrence of the boundary in the code.

    For instance, the loop boundary is 10000 and represents the maximum number of client connections supported in a network server application. If the server supports more clients, you must change all instances of the loop boundary in your code. Even if the loop boundary occurs once, you have to search for a numerical value of 10000 in your code. The numerical value can occur in places other than the loop boundary. You must browse through those places before you find the loop boundary.

Fix

Use a symbolic name instead of a hard-coded constant for loop boundary. Symbolic names include const-qualified variables, enum constants or macros.enum constants are recommended because:

  • Macros are replaced by their constant values after preprocessing. Therefore, they can expose the buffer size.

  • enum constants are known at compilation time. Therefore, compilers can allocate storage for them more efficiently.

    const-qualified variables are usually known at run time.

Examples

expand all

void performOperation(int);

void func(void) {
    for (int i=0; i<100; i++)
        performOperation(i);
}

In this example, the boundary of the for loop is hard-coded.

Correction — Use Symbolic Name

One possible correction is to replace the hard-coded loop boundary with a symbolic name.

const int MAX_1 = 100;
#define MAX_2 100
enum { MAX_3 = 100 };

void performOperation_1(int);
void performOperation_2(int);
void performOperation_3(int);

void func(void) {
    for (int i=0; i<MAX_1; i++)
        performOperation_1(i);
    for (int i=0; i<MAX_2; i++)
        performOperation_2(i);
    for (int i=0; i<MAX_3; i++)
        performOperation_3(i);
}

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: HARD_CODED_LOOP_BOUNDARY
Impact: Low

Version History

Introduced in R2015b