Most programmers prefer to write code over debugging it. Unfortunately, code breaks a lot more often than we would like and it often breaks in situations that are hard to debug. Therefore, an essential skill as a programmer is to know how to debug your code (and that of others).
When facing our first bug we all start out with what is called printf debugging. That means we add lines of code that call printf (or any other print function) at relevant places in our code and output values of variables or just print a message that indicates that the execution of the program has reached this particular line in the code. Then we recompile the program, run it, reproduce the problem, and add more printf calls until we find the bug.
There is nothing wrong with printf debugging. It is the most basic method of debugging and it works quite well in many situations and is available to the programmer in nearly any environment. Lots of programs even write a log file during normal operation to help track down problems that happened in production. Log files are nothing else than built-in, glorified printf debugging.
printf debugging is great but it has its limitations. For example, you can’t step through a program line by line or just jump into a specific location and look around exploring the variables and the state of the program at the time.
Whenever you want to check a new variable or data structure that wasn’t on your radar before you have to add new printf statements to the code, recompile it, run it, and get the program into the desired error state. Also, there is no way to halt the program every time a certain variable or memory address is read or modified and see from which line of code the memory access happened.
All these things and more can be done with a debugger. And that is why it is crucial to know a good debugger and know it well.
One of the most popular and powerful debuggers is gdb. And it is also available on more platforms than probably any other debugger. This article will show you everything you need to know to debug your own programs with gdb.
Fixing a simple Crash
Let’s say you write a program in C or C++ and it crashes. While in languages like Java or Python, you will get a full-fledged stack trace all you get in our case is the message “Segmentation fault” in the terminal from which you started your program.
Continue reading “Getting started with GDB” →