Finding infinite loops with sampling

We could continue using next to move through our program's execution, but since we don't know where the bug lies this might not be a very useful technique. Instead, remember that the problem with our program is that it seemed to be running forever. This sounds a lot like an infinite loop!

So rather than stepping through our code, we'll simply let it execute and then we'll use Ctrl+C to break back into the debugger when we think we might be in that loop:

(Pdb) cont
^C
Program interrupted. (Use 'cont' to resume).
> /Users/sixty_north/examples/palindrome.py(9)digits()
-> x = mod
(Pdb)

After letting the program run for a few seconds, we press Ctrl+C which halts the program and shows us that we're in the the digits() function of palindrome.py. If we want to see the source code at that line, we can use the PDB command list:

(Pdb) list
4 "Convert an integer into a list of digits."
5 digs = []
6 while x != 0:
7 div, mod = divmod(x, 10)
8 digs.append(mod)
9 -> x = mod
10 return digs
11
12 def is_palindrome(x):
13 "Determine if an integer is a palindrome."
14 digs = digits(x)
(Pdb)

We see that this is indeed inside a loop, which confirms our suspicion that an infinite loop might be involved.

We can use the return command to try to run to the end of the current function. If this doesn't return, we'll have very strong evidence that this is an infinite loop:

(Pdb) r

We let this run for a few seconds to confirm that we never exit the function, and then we press Ctrl+C. Once we get back to a PDB prompt, let's exit PDB with the quit command:

(Pdb) quit
%
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset