Infinite loop: Difference between revisions

Content deleted Content added
m Reverting possible vandalism by 2A00:1370:8192:2B9D:6516:B70A:9DD6:EDAC to version by Jochen Burghardt. Report False Positive? Thanks, ClueBot NG. (4200867) (Bot)
Link suggestions feature: 3 links added.
 
(36 intermediate revisions by 26 users not shown)
Line 1:
{{shortShort description|Programming idiom}}
{{About-distinguish|the programming term|the street named after this term|Infinite Loop (street)|the book by Michael S. Malone|Infinite Loop (book)}}
{{Redirect-distinguish|Endless loop|EP by Eiko Shimamiya|Endless Loop (album)}}
{{Loop constructs}}<!-- NOTE:DO Please don'tNOT remove. Discuss navigation concept at [[Talk:Do_while_loopDo while loop#Helpbox_experimentHelpbox experiment]] -->
 
In [[computer programming]], an '''infinite loop''' (or '''endless loop''')<ref>{{cite web
|url=https://www.yourdictionary.com/endless-loop
|title=Endless loop dictionary definition
|access-date=2020-01-22
|archive-date=2020-08-01
|archive-url=https://web.archive.org/web/20200801213748/https://www.yourdictionary.com/endless-loop
|url-status=live
}}</ref><ref>{{cite web
|url=https://whatis.techtarget.com/definition/infinite-loop-endless-loop
|title=What is infinite loop (endless loop)
|access-date=2020-01-22
|archive-date=2019-07-15
|archive-url=https://web.archive.org/web/20190715101446/https://whatis.techtarget.com/definition/infinite-loop-endless-loop
|url-status=live
}}</ref> is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, ("pullsuch theas turning off power via a switch or pulling a plug"). It may be intentional.
 
There is no general algorithm to determine whether a computer program contains an infinite loop or not; this is the [[halting problem]].
 
==Overview==
*This differs from "a type of computer program that runs the same instructions continuously until it is either stopped or interrupted.".<ref>{{cite news
This differs from:
|newspaperwork=[[The New York Times]]
* "a type of computer program that runs the same instructions continuously until it is either stopped or interrupted."<ref>{{cite news
|url=https://archive.nytimes.com/www.nytimes.com/library/tech/99/08/biztech/articles/16digi.html
|newspaper=[[The New York Times]]
|title=Overload of Hangers-On Creates Bumpy Ride for Internet Stocks
|url=https://archive.nytimes.com/www.nytimes.com/library/tech/99/08/biztech/articles/16digi.html
|last=Caruso |first=Denise
|title=Overload of Hangers-On Creates Bumpy Ride for Internet Stocks
|access-date=August 1516, 20151999
|author=Denise Caruso
|access-date=AugustDecember 1627, 19992019
|accessarchive-date=December 27, 2019
|archive-url=https://web.archive.org/web/20191227145519/https://archive.nytimes.com/www.nytimes.com/library/tech/99/08/biztech/articles/16digi.html
|archive-date=December 27, 2019
|url-status=live
|archive-url=https://web.archive.org/web/20191227145519/https://archive.nytimes.com/www.nytimes.com/library/tech/99/08/biztech/articles/16digi.html
}}</ref> Consider the following [[pseudocode]]:
|url-status=live
}}</ref>
 
Consider the following [[pseudocode]]:
<syntaxhighlight lang="lua">
how_many = 0
Line 59 ⟶ 57:
==Details==
An ''infinite loop'' is a sequence of instructions in a [[computer program]] which loops endlessly, either due to the [[control flow#Loops|loop]] having no terminating condition,<ref>{{cite magazine
|magazine=Flow Journal
|url=http://www.flowjournal.org/tag/loop-media/?print=print-search
|title=Codes and Modes: The Character of Documentary Culture
|quote=an infinite loop is one that lacks .. an exit condition
|date=November 2014
|access-date=2020-01-23
|archive-date=2020-08-01
|archive-url=https://web.archive.org/web/20200801213624/http://www.flowjournal.org/tag/loop-media/?print=print-search
|url-status=live
}}</ref> having one that can never be met, or one that causes the loop to start over. In older [[operating system]]s with [[cooperative multitasking]],<ref>also known as non-preemptive-multitasking: {{cite magazine
|author=<!-- Unstated -->
|magazine=[[PC Magazine]]
|url=https://www.pcmag.com/encyclopedia/term/48051/non-preemptive-multitasking
|title=Non-preemptive Multitasking
|access-date=August 15, 2015
|archiveaccess-date=JulyFebruary 267, 20192024
|archive-date=DecemberJuly 2726, 2019
|archive-url=https://web.archive.org/web/20190726232111/https://www.pcmag.com/encyclopedia/term/48051/non-preemptive-multitasking
|url-status=live
}}</ref> infinite loops normally caused the entire system to become unresponsive. With the now-prevalent preemptive multitasking model, infinite loops usually cause the program to consume all available processor time, but can usually be terminated by thea user. [[Busy waiting|Busy wait]] loops are also sometimes called "infinite loops". Infinite loops are one possible cause for a computer "[[hangHang (computing)|hanging or freezing]]"; others include [[thrashingThrashing (computer science)|thrashing]], [[deadlock (computer science)|deadlock]], and [[segmentation fault|access violation]]s.
 
==Intended vs unintended looping==
Looping is repeating a set of instructions until a specific condition is met. An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop.
 
===Intentional looping===
Line 85 ⟶ 84:
 
Modern interactive computers require that the computer constantly be monitoring for user input or device activity, so at some fundamental level there is an infinite processing [[idle loop]] that must continue until the device is turned off or reset. In the [[Apollo Guidance Computer]], for example, this outer loop was contained in the Exec program,<ref>{{cite web
|url=http://klabs.org/history/history_docs/mit_docs/1711.pdf
|title=The History of Apollo On-board Guidance, Navigation, and Control
|author=David Hoag
|date=September 1976
|publisher=Charles Stark Draper Laboratory
|access-date=2020-01-23
|archive-date=2016-11-05
|archive-url=https://web.archive.org/web/20161105060425/http://klabs.org/history/history_docs/mit_docs/1711.pdf
|url-status=live
}}</ref> and if the computer had absolutely no other work to do, it would loop run a dummy job that would simply turn off the "computer activity" indicator light.
 
Modern computers also typically do not halt the processor or motherboard circuit-driving clocks when they crash. Instead they fall back to an error condition displaying messages to the operator (such as the [[blue screen of death]]), and enter an infinite loop waiting for the user to either respond to a prompt to continue, or to reset the device.
 
==== Spinlocks ====
[[Spinlock|Spinlocks]] are low-level synchronization mechanisms used in concurrent programming to protect shared resources. Unlike traditional locks that put a thread to sleep when it can't acquire the lock, spinlocks repeatedly "spin" in an infinite loop until the lock becomes available. This intentional infinite looping is a deliberate design choice aimed at minimizing the time a thread spends waiting for the lock and avoiding the overhead of higher level synchronisation mechanisms such as [[Lock (computer science)|mutexes]].
 
====Multi-threading====
In multi-threaded programs some threads can be executing inside infinite loops without causing the entire program to be stuck in an infinite loop. If the main thread exits, all threads of the process are forcefully stopped, thus all execution ends and the process/program terminates. The threads inside the infinite loops can perform "housekeeping" tasks or they can be in a blocked state waiting for input (from socket/queue) and resume execution every time input is received.
 
===Unintentional looping===
[[File:Infinite loop BSOD.jpg|thumb|A [[blue screen of death]] on [[Windows XP]]. "The [[device driver]] got stuck in an infinite loop."]]
Most often, the term is used for those situations when this is not the intended result; that is, when this is a [[software bug|bug]].<ref>{{cite web
|url=https://nyxcrossword.com/2013/10/1013-13-new-york-times-crossword.html
|title=New York Times Crossword Answers
|quote=computing .. a defect .. which .. to loop
|date=October 13, 2013
|access-date=January 22, 2020
|archive-date=August 2, 2020
|archive-url=https://web.archive.org/web/20200802040416/https://nyxcrossword.com/2013/10/1013-13-new-york-times-crossword.html
|url-status=live
}}</ref> Such errors are most common amongby novice programmers, but can be made by experienced programmers as wellalso, because their causes can be quite subtle.
 
One common cause, for example, is that thea programmer intends to iterate over sequence of nodes in a [[data structure]] such as a [[linked list]] or [[treeTree (data structure)|tree]], executing the loop code once for each node. Improperly formed links can create a ''reference loop'' in the data structure, where one node links to another that occurs earlier in the sequence. This makes part of the data structure into a [[ringRing (data structure)|ring]], causing naive code to loop forever.
 
While most infinite loops can be found by close inspection of the code, there is no ''general'' method to determine whether a given program will ever halt or will run forever; this is the [[undecidable problem|undecidability]] of the [[halting problem]].<ref>{{cite web|url=https://www.geeksforgeeks.org/halting-problem-in-theory-of-computation|title=Halting Problem in Theory of Computation|date=3 October 2018|access-date=22 January 2020|archive-date=9 August 2020|archive-url=https://web.archive.org/web/20200809100104/https://www.geeksforgeeks.org/halting-problem-in-theory-of-computation/|url-status=live}}</ref>
 
==Interruption==
As long as the system is responsive, infinite loops can often be interrupted by sending a signal to the process (such as [[SIGINT (POSIX)|SIGINT]] in Unix), or an [[interrupt]] to the processor, causing the current process to be aborted. This can be done in a [[task manager]], in a terminal with the [[Control-C]] command,<ref>{{cite web
|url=https://pen-testing.sans.org/resources/papers/gcih/buffer-overflow-exploit-dameware-remote-control-software-104168
|title=A Buffer Overflow Exploit Against the DameWare Remote Control software
|quote=As soon as the command shell is closed with a control-c combination ...
|date=December 19, 2003
|access-date=January 22, 2020
|archive-date=July 24, 2020
|archive-url=https://web.archive.org/web/20200724200739/https://pen-testing.sans.org/resources/papers/gcih/buffer-overflow-exploit-dameware-remote-control-software-104168
|url-status=live
}}</ref> or by using the [[killKill (command)|kill]] command or [[system call]]. However, this does not always work, as the process may not be responding to signals or the processor may be in an uninterruptible state, such as in the [[Cyrix coma bug]] (caused by overlapping uninterruptible instructions in an [[instruction pipeline]]). In some cases other signals such as [[SIGKILL]] can work, as they do not require the process to be responsive, while in other cases the loop cannot be terminated short of system shutdown.
 
==Language support==
{{see also|Control flow}}
Infinite loops can be implemented using various [[control flow]] constructs. Most commonly, in unstructured programming this is jump back up ([[goto]]), while in [[structured programming]] this is an indefinite loop ([[while loop]]) set to never end, either by omitting the condition or explicitly setting it to true, as <code>while (true) ...</code>.
 
Some languages have special constructs for infinite loops, typically by omitting the condition from an indefinite loop. Examples include Ada (<code>loop ... end loop</code>),<ref>[[b:Ada Programming/Control#Endless Loop|Ada Programming: Control: Endless Loop]]</ref> Fortran (<code>DO ... END DO</code>), Go (<code>for { ... }</code>), Ruby (<code>loop do ... end</code>), and Rust (<code>loop { ... }</code>).
Line 138 ⟶ 141:
A simple example (in [[C (programming language)|C]]):
 
<syntaxhighlight lang="c" line="1">
#include <stdio.h>
 
Line 144 ⟶ 147:
{
for (;;) // or equivalently, while (1)
printf("Infinite Loop\n");
return 0;
}
Line 153 ⟶ 156:
 
A similar example in 1980s-era [[BASIC programming language|BASIC]]:
<syntaxhighlight lang="gwbasicbasic">
10 PRINT "INFINITE LOOP"
20 GOTO 10
</syntaxhighlight>
 
A similar example in [[MS-DOS]] compatible batch files:
<syntaxhighlight lang="bat">
:A
Line 164 ⟶ 167:
goto :A
</syntaxhighlight>
Here the loop is quite obvious, as the last line unconditionally sends execution back to the first.
 
An example inIn [[Java (programming language)|Java]]:
<syntaxhighlight lang="java">
while (true) {
Line 173 ⟶ 175:
</syntaxhighlight>
 
The while loop never terminates because its condition is always true.
An example in [[Bourne Again Shell]]
 
An example inIn [[Bourne Again Shell]]:
<syntaxhighlight lang="bash">
for ((;;)); do
Line 180 ⟶ 184:
</syntaxhighlight>
 
An example inIn [[Rust (programming language)|Rust]]:
<syntaxhighlight lang="rust">
loop {
Line 191 ⟶ 195:
===Mathematical errors===
Here is one example of an infinite loop in [[Visual Basic]]:
<syntaxhighlight lang=vbvbnet>
dim x as integer
do while x < 5
Line 199 ⟶ 203:
 
</syntaxhighlight>
This creates a situation where <code>x</code> will never be greater than 5, since at the start of the loop code, <code>x</code> is givenassigned the value of 1, thus,(regardless of any previous value) before it is changed to <code>x</code> + 1. Thus the loop will always endresult in 2<code>x</code> and= the2 loopand will never break. This could be fixed by moving the <code>x = 1</code> instruction outside the loop. Essentiallyso whatthat thisits infiniteinitial loop doesvalue is toset instruct a computer to keep on adding 1 to 1 until 5 is reached. Since 1+1 always equals 2, this will neveronly happenonce.
 
In some languages, programmer confusion about the mathematical symbols may lead to an unintentional infinite loop. For example, here is a snippet in [[C (programming language)|C]]:
<syntaxhighlight lang=c>
#include <stdio.h>
Line 218 ⟶ 222:
</syntaxhighlight>
 
The expected output is the numbers 0 through 9, with an interjected "a equals 5!" between 5 and 6. However, in the line "<code>if (a = 5)</code>" above, the programmer has confused the = (assignment) operator was confused with the == (equality test) operator. Instead, this will assign the value of 5 to <code>a</code> at this point in the program. Thus, <code>a</code> will never be able to advance to 10, and this loop cannot terminate.
 
===Rounding errors===
 
{| style="float:right; border: 1px solid grey;"
|-
Line 278 ⟶ 281:
 
==Multi-party loops==
An infinite loop may be caused by several entities interacting. Consider a server that always replies with an [[error message]] if it does not understand the request. Even if there is no possibility for an infinite loop within the server itself, a system comprising two of them (''A'' and ''B'') may loop endlessly: if ''A'' receives a message of unknown type from ''B'', then ''A'' replies with an error message to ''B''; if ''B'' does not understand the error message, it replies to ''A'' with its own error message; if ''A'' does not understand the error message from ''B'', it sends yet another error message, and so on.
 
One common example of such situation is an [[email loop]]. An example of an email loop is if someone receives mail from a no reply inbox, but their auto-response is on. They will reply to the no reply inbox, triggering the "this is a no reply inbox" response. This will be sent to the user, who then sends an auto reply to the no-reply inbox, and so on and so forth.
 
==Pseudo-infinite loops==
Line 292 ⟶ 295:
done
</syntaxhighlight>
 
===Impossible termination condition===
An example [[for loop]] in [[C (programming language)|C]]:
Line 303 ⟶ 307:
 
===Infinite recursion===
*[[{{Main|Recursion (computer science)]]#Infinite recursion}}
Infinite recursion is a special case of an infinite loop that is caused by [[recursion (computer science)|recursion]].
 
The following example in [[Visual Basic for Applications|VBA]] (VBA) returns a [[stack overflow]] error:
<syntaxhighlight lang="vbvbscript">
Sub Test1()
Call Test1
Line 324 ⟶ 329:
 
===Alderson loop===
''Alderson loop'' is a rare slang or [[The Jargon File|jargon]] term for an infinite loop where there is an exit condition available, but inaccessible in the currentan implementation of the code, typically due to a programmer's error. These are most common and visible while [[debugging]] [[user interface]] code.
 
A C-like pseudocode example of an Alderson loop, where the program is supposed to sum numbers given by the user until zero is given, but where the programmerwrong hasoperator is used the wrong operator:
<syntaxhighlight lang="C">
int sum = 0;
Line 342 ⟶ 347:
</syntaxhighlight>
 
The term allegedly received its name from a programmer (whose last name is Alderson) who in 1996<ref>{{cite web
|url=https://www.lee-dohm.com/2013/05/24/alderson-loop
|title=Alderson loop
|author=Lee Dohm
|date=May 24, 2013
|access-date=January 22, 2020
|archive-date=June 19, 2020
|archive-url=https://web.archive.org/web/20200619200434/https://www.lee-dohm.com/2013/05/24/alderson-loop/
|url-status=live
}}</ref> had coded a [[modal window|modal]] [[dialog box]] in [[Microsoft Access]] without either an OK or Cancel button, thereby disabling the entire program whenever the box came up.<ref>{{Cite web |url=http://www.catb.org/~esr/jargon/html/A/Alderson-loop.html |title=Alderson Loop |website=[[The Jargon File]], Version 4.4.7 |url-status=live |archive-url=https://web.archive.org/web/20060515053043/http://www.catb.org/~esr/jargon/html/A/Alderson-loop.html |archive-date=2006-05-15 |access-date=2006-05-21}}</ref>
 
==See also==
{{portal|Mathematics}}
*[[Cycle detection]]
*[[Deadlock]]
*[[Divergence (computer science)]]
*[[Fork bomb]] (an infinite loop is one of two key components)
*[[Goto]]
*[[Infinite regress]]
*[[Recursion (computer science)]]
 
==References==
{{Reflist}}
<references/>
 
==External links==
Line 370 ⟶ 372:
 
{{DEFAULTSORT:Infinite Loop}}
[[Category:Control flow]]
[[Category:Iteration in programming]]
[[Category:Programming language comparisons]]
[[Category:Recursion]] <!-- notNot directly relevant -->
[[Category:Software bugs]]
<!-- Hidden categories below -->
[[Category:Articles with example BASIC code]]
[[Category:Articles with example C code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example Rust code]]