4

How would you determine a loop is a infinite loop and will break out of it.

Does anyone has the algorithm or can assist me on this one.

Thanks

Pankaj Gupta
  • 81
  • 1
  • 11
  • 2
    My guess is that there's no sure way that computer recognizes something as infinite loop. You have to be aware of it as a code engineer. – darijan Mar 16 '12 at 14:01
  • But some intelligent language compiler understand and get you out of the loop if such thing happens. – Pankaj Gupta Mar 16 '12 at 14:03
  • 3
    It's easy, just wait for infinity and see if the program has terminated. – aioobe Mar 16 '12 at 14:03
  • While I don't think @amit's response below is logically valid, I also don't think there always exists a way to determine if something will loop indefinitely. For example, you could always construct a function whose limit (for some value of parameters) cannot be calculated except numerically---thus you would have to perform the calculation to tell if some end case would result or not (and thus if the loop would perform one way or another). In special cases, making the determination could be done easily analytically, or by trial of the loop.... – DilithiumMatrix Mar 16 '12 at 15:46

2 Answers2

8

There is no general case algorithm that can determine if a program is in an infinite loop or not for every turing complete language, this is basically the Halting Problem.

The idea of proving it is simple:

  1. Assume you had such an algorithm A.
  2. Build a program B that invokes A on itself [on B].
  3. if A answers "the program will halt" - do an infinite loop
  4. else [A answers B doesn't halt] - halt immidiately

Now, assume you invoke A on B - the answer will be definetly wrong, thus A doesn't exist.

Note: the above is NOT a formal proof, just a sketch of it.

amit
  • 175,853
  • 27
  • 231
  • 333
  • OK..what if you are said to traverse a long row of data that is connected to some point of same row. Is this a particular case of Halting problem or you have any algo associated to solve it? – Pankaj Gupta Mar 16 '12 at 14:07
  • 3
    @PankajGupta: If I am not mistaken - for each program `A`, there is a program `B` that can determine if `A` will halt. There is no **general case** algorithm, that can determine if a program halts or not - for **all programs**. – amit Mar 16 '12 at 14:10
5

As written by others, it cannot be determined.

However, if you want to have some checking, you can use the WatchDog design pattern. This is a separate thread that checks if a task still is active. Your own thread should give a signal regularly to say it is alive. Make sure this signal is not set inside your (infinite) loop.

If there was no signal, the program is inside an infinite loop or has stopped and the watchdog can act on it.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119