Next: , Previous: Compiling Programs, Up: Top


5 Debugging

Parts of this chapter are adapted from Don't Panic: A 6.001 User's Guide to the Chipmunk System, by Arthur A. Gleckler.

Even computer software that has been carefully planned and well written may not always work correctly. Mysterious creatures called bugs may creep in and wreak havoc, leaving the programmer to clean up the mess. Some have theorized that a program fails only because its author made a mistake, but experienced computer programmers know that bugs are always to blame. This is why the task of fixing broken computer software is called debugging.

It is impossible to prove the correctness of any non-trivial program; hence the Cynic's First Law of Debugging:

Programs don't become more reliable as they are debugged; the bugs just get harder to find.

Scheme is equipped with a variety of special software for finding and removing bugs. The debugging tools include facilities for tracing a program's use of specified procedures, for examining Scheme environments, and for setting breakpoints, places where the program will pause for inspection.

Many bugs are detected when programs try to do something that is impossible, like adding a number to a symbol, or using a variable that does not exist; this type of mistake is called an error. Whenever an error occurs, Scheme prints an error message and starts a new REPL. For example, using a nonexistent variable foo will cause Scheme to respond

     1 ]=> foo
     
     ;Unbound variable: foo
     ;To continue, call RESTART with an option number:
     ; (RESTART 3) => Specify a value to use instead of foo.
     ; (RESTART 2) => Define foo to a given value.
     ; (RESTART 1) => Return to read-eval-print level 1.
     
     2 error>

Sometimes, a bug will never cause an error, but will still cause the program to operate incorrectly. For instance,

     (prime? 7)   =>   #f

In this situation, Scheme does not know that the program is misbehaving. The programmer must notice the problem and, if necessary, start the debugging tools manually.

There are several approaches to finding bugs in a Scheme program:

Only experience can teach how to debug programs, so be sure to experiment with all these approaches while doing your own debugging. Planning ahead is the best way to ward off bugs, but when bugs do appear, be prepared to attack them with all the tools available.