Weakness reference
CWE-835

Loop with Unreachable Exit Condition (Infinite Loop)

An infinite loop occurs when a program enters a loop that never terminates because its exit condition can never be met. This causes the application to consume…

01Summary

An infinite loop occurs when a program enters a loop that never terminates because its exit condition can never be met. This causes the application to consume CPU, memory, or other resources indefinitely, leading to performance degradation, denial of service, or system crashes. Unlike intentional infinite loops (which are rare but valid in event handlers or servers), this weakness arises from logic errors that make the loop condition unreachable under normal operation.

02How It Happens

Infinite loops typically result from one of three patterns: a loop condition that is never updated (e.g., a counter that should increment but doesn't), a condition that contradicts the loop's purpose (e.g., while (x != 0) when x is never modified inside the loop), or a logic error where the exit condition is checked against the wrong variable. The developer may intend for a variable to change during iteration, but due to a typo, missing assignment, or incorrect control flow, the variable remains static. Over time, the loop consumes resources until the process is terminated or the system runs out of memory.

03Real-World Impact

An infinite loop can render an application unresponsive, freeze a user interface, or crash a server. In multi-threaded environments, a single thread stuck in an infinite loop may block other operations. On resource-constrained systems (embedded devices, containers, serverless functions), the resource exhaustion can trigger cascading failures. If the loop is triggered by user input or a network request, an attacker can deliberately cause the condition and mount a denial-of-service attack against the application or its host.

04Vulnerable & Fixed Patterns

Vulnerable pattern
def process_items(items):
    index = 0
    while index < len(items):
        item = items[index]
        print(f"Processing: {item}")
        # Bug: index is never incremented
    return "Done"

Why it's vulnerable:
The loop condition index < len(items) is checked, but index is never incremented inside the loop body. The condition will always be true (assuming items is not empty), causing an infinite loop.

Fixed pattern
def process_items(items):
    index = 0
    while index < len(items):
        item = items[index]
        print(f"Processing: {item}")
        index += 1  # Increment the counter
    return "Done"
Vulnerable pattern
function fetch_records($limit) {
    $count = 0;
    while ($count < $limit) {
        $record = get_next_record();
        echo "Record: " . htmlspecialchars($record) . "\n";
        // Bug: $count is never incremented
    }
    return "Fetched";
}

Why it's vulnerable:
The loop increments based on $count < $limit, but $count is never modified inside the loop. If $limit is greater than 0, the loop will never exit.

Fixed pattern
function fetch_records($limit) {
    $count = 0;
    while ($count < $limit) {
        $record = get_next_record();
        echo "Record: " . htmlspecialchars($record) . "\n";
        $count++;  // Increment the counter
    }
    return "Fetched";
}

05Prevention Checklist

Review loop conditions carefully:
Ensure the exit condition references a variable that is actually modified inside the loop body.
Use for-loops when iterating over collections:
for loops with explicit counters are less prone to infinite loops than while loops with manual counter management.
Add loop guards or timeouts:
For loops that depend on external state (network calls, file reads), implement a maximum iteration count or timeout to prevent runaway execution.
Enable static analysis tools:
Use linters and code analyzers that can detect unreachable exit conditions or unused variable assignments.
Test with edge cases:
Run unit tests with boundary conditions (empty collections, single items, large datasets) to catch loops that fail to terminate.
Monitor resource usage in production:
Set up alerts for CPU spikes or memory growth that may indicate an infinite loop has been triggered.

06Signs You May Already Be Affected

- A process or thread consistently uses 100% CPU with no apparent work being done, or CPU usage spikes unexpectedly after a specific user action or input. - Application logs show repeated identical messages or no progress in a task that should complete within a known timeframe. - The application becomes unresponsive or hangs, and restarting the process is the only way to recover normal operation.

07Related Recent Vulnerabilities