Basic GDB Tutorial

So, you believe there are bugs in your C/C++ code or you have encountered SEGFAULT while executing your code. What will you do?

  1. write a lot of printf statements at various places in your code under suspicion
  2. use gdb (GNU code debugger)

This article is about Approach 2

Disclaimer : This article is just a basic gdb tutorial and is nowhere meant to be comprehensive.

Using GDB

  1. Compile code using -ggdb switch For example, g++ -ggdb -o hellowworld
  2. Run your code under gdb using gdb helloworld
  3. Set a breakpoint at location where you suspect the problem to be. For example, if you suspect problem could be at line 12 then set breakpoint at line 12 using break 12 elesewise, you can set breakpoint at function also. For example break main will stop the code execution as soon as main function is called.
  4. now run the code using run
  5. If the program crashes then set the breakpoint at a different [much earlier] location.
  6. Now the code has stopped execution, you can continue step by step execution using step or you can continue the execution continously using continue or you can print the values of various variables at this stage using print var_name
  7. To find the stack trace use backtrace
  8. use quit to exit gdb [and stop to stop a program which is still under execution]

Happy code debugging


  1. GDB Man page

Leave a Reply