August 23, 2007
The first rule of debugging
If you've been programming for more than, oh, a few minutes, you've discovered that your programs don't always work as you intended.
Most beginners' first reaction when they make such discoveries is to think that there is something wrong with the compiler. After being disabused of that notion, they will reluctantly go looking for the problem.
However, my experience is that many programmers, especially beginners, make a critical mistake when they go on their bug hunts.
The mistake is in failing to be sure that the program that they are trying to debug is actually the program that they are running.
For example, before you ran your program, did you compile it? Are you sure? Are you sure that you compiled every piece of source code that you're using? With the same compiler? Are you sure that you saved the code before you compiled it.
I've lost track of how many times I've had a program crash on me, then removed all object and executable files, then recompiled everything from scratch, and had it work perfectly.
Oh yes, one other thing. Many operating systems have a notion of a search path, which is a list of places where the system should look for a program when you run it. Sometimes, the system is set up in such a way that when you try to execute a program, you are unwittingly getting a program with the same name from somewhere else. For example, on many Unix systems, typing a.out might execute a file named a.out wherever in the search path it happens to be, whereas typing ./a.out will insist on executing a.out in the current directory.
Whatever facilities your operating system happens to have, you will save yourself a lot of time if you remember the first rule: Before you go to fix it, be sure you're fixing the right thing.
Posted by Andrew Koenig at 11:00 AM Permalink
|