Debugging
Debugging
There are two major phases of debugging activities:
- Preventing bugs
- Detecting/locating bugs
Well-established fact: It is much more expensive (in terms
of time and effort) to detect/locate existing bugs, than to prevent
them in the first place.
Bug Location
The primary rule of debugging is:
Use the process of elimination!
- Many students do not know where to start when looking for a bug
- Any bug you are looking for is probably not where you think
it is (or you would have found it already!)
- To locate a bug, split your code into "regions"
- Try to show that the bug is not in each region
- If you can show this, you can eliminate that region from
consideration
- Eliminate regions one by one, until you've located the problem
Splitting Code Into Regions
- If you are using a debugger:
- Set breakpoints between regions
- If no debugger is available:
- Add print statements between regions
Examine Intermediate Values
- If you are using a debugger:
- While running the program, inspect the values of
important intermediate results at each breakpoint
- If no debugger is available:
- Print out the values of important intermediate results in
the print statements between regions
- Never assume you know what is happening to a
variable or value--always inspect its value. It
is far too easy to "think" one thing is happening while the code
is actually doing another!
Use Intermediate Values To Narrow Scope
- By checking intermediate values for appropriateness, you
should be able to determine:
- If the program is operating properly on entry into the
region
- If the program is operating properly on exit from the
region
- If the program is operating properly on entry to and exit from
the region, then the bug probably is not inside the
region
- If the program is not operating properly on
entry, then the bug must be before the region
- If the program is not operating properly on
exit, then the bug must be before the
end of the region
- If the program is operating properly on entry,
but is not operating properly on exit, then the
bug must be inside the region
Once You've Found the Faulty Region
Once you've found the region:
- You may be able to see the bug by carefully inspecting the
code, now that you know what series of statements the bug must be
in
- Often, you still may not be able to spot the bug
- So, use the process of elimination:
- Further divide the faulty region into subregions
- Inspect intermediate values at the boundaries
- Determine which subregion contains the fault
- Repeat as many times as necessary
- Don't feel bad--some bugs are difficult enough to see that you
end up putting print statements or breakpoints between
every statement
Stephen Edwards <edwards@cs.vt.edu>
Last modified: Sun Mar 16 21:07:53 EST 1997