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?
- write a lot of printf statements at various places in your code under suspicion
- 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.
- Compile code using -ggdb switch For example, g++ -ggdb -o hellowworld helloworld.cc
- Run your code under gdb using gdb helloworld
- Set a breakpoint at the location where you suspect the problem to be. For example, if you suspect the problem could be at line 12 then set breakpoint at line 12 using break 12 likewise, you can set a breakpoint at the function also. For example, break main will stop the code execution as soon as the main function is called.
- now run the code using run
- If the program crashes then set the breakpoint at a different [much earlier] location.
- Now the code has stopped the execution, you can continue step-by-step execution using a step or you can continue the execution continuously using continue or you can print the values of various variables at this stage using print var_name
- To find the stack trace use backtrace
- use quit to exit gdb [and stop to stop a program that is still under execution]
Happy code debugging
- GDB Man page