the philosophy of debugging
Dear class,
As you are finishing up malloc, we wanted to give a few pointers on debugging.
Many of you are used to using “higher level” programming languages i.e. Java, Python, Scheme which provide helpful error messages when your program crashes. That friendliness is gone when we’re using a language like C. All you will see from now on is the infamous Segmentation Fault. Typically, these are the debugging behaviors we have observed
- Student looks at code and doesn’t know why it’s wrong.
- Student runs their code in gdb and knows which line the error is on and examines that line and only that line intently.
- Student prints out the values used in that line which it segfaulted on.
For bugs, and even more so with memory bugs, it will often be the case that the error is a result of an invalid operation many lines ago. This means you can’t just inspect the code where the Segfault occurred on. You have to look at more code and potentially all of the code that led to the segfault. Bugs occur when what you think wasn’t going to happen did in fact occur OR what you did think was going to happen didn’t happen.
Thus, the philosophy of debugging is simply to CONFRONT THE FACTS.
- Isolate the problem, conduct a binary search on your code and find out when the bug occurs. Try to build a smaller and smaller test until you can no longer recreate your bug.
- Find the facts and scrutinize them. Start from the smallest guarantee and build it up. Assume everything is wrong and prove that your program is right with facts.
- Debugging means providing yourself with the context information on where the bug was created, where did things started looking fishy?
In practice, this translates into three things
- Checkers: use asserts to prove your program is right. Every assumption you make in your code should be accompanied by an assert, even if it’s as simple Do something like assert(“next block is null!” && (NEXT_BLOCK(bp) != NULL)) Since assert prints itself when it fails, you can see what went wrong in words rather than just in code.
- Print statements: provide yourself with the context information.
- Write simple test files to recreate your bug.
Formalize these debugging tools. Turn them into functions in your code which you can just use when you see another bug.
TL;DR After I received a lot of emails from students about not knowing how to debug, I wrote some debugging advice which I think is necessary for any aispiring programmer.
blog comments powered by Disqus