Infinite Loops

Entering an infinite loop is one of the worst ways a program can fail. It may not be as insidious as a bug that subtly corrupts data, nor as attention-demanding as an exception being thrown, but like the latter, it generally results in the end of a process’s execution. Worse, it ties up the CPU, doesn’t leave a stack trace, and can be difficult to diagnose.

There are a number of ways that you can inadvertently create an infinite loop: two methods that call each other, a loop with a failing end condition, or an endless tail recursion.

I don’t write do/while loops frequently, largely because of the possibility of an infinite loop being created, but sometimes they are the best solution for a problem. In cases like these, I also build what I call an escape valve, so I can choose to crash the program if an infinite loop is detected. An infinite loop is often caused by incorrect program behaviour, so sometimes crashing the program for the purpose of debugging is preferable to attempting to keeping it running.

An escape valve essentially keeps track of the number of iterations of a loop, and breaks out of the loop if that number is considerably higher than logic would dictate, or is large enough to be undesirable. Here’s a pseudocode example:


var iterations = 0;
var score = new Score();
var infiniteLoop = false;
do
{
    simulateOneSecond(score);
    iterations++;
    if( iterations > 10000 )
    {
        infiniteLoop = true;
        break;
    }
}
while( score.isTied() );

In this code, I’m running a simulation of a single second of a sports match. The simulation continues until the tie is broken. This is generally something that happens relatively quickly, so I put a check in the loop to see if it has taken much longer than normal. In this particular case, I might choose not to crash the program if this happens, and I would likely be inclined to log this behaviour and allow the simulation to continue. I would then examine the logs after the fact for any failures.

I use this feature now in all do/while loops that I create. It’s relatively easy to do, and the benefits are clear.

Next task: develop a strategy to protect against other types of infinite loops.

Leave a Reply

Your email address will not be published. Required fields are marked *