How to use GNU Debugger(GDB)

Posted: January 31, 2013 in Linux, Programming

One of the best tool which can recover you from erros is GNU Debugger
(GDB) . GDB has got a numerous options through which we can resolve our errors. When dealing
with “Segmentation errors”.

i feed GDB is the best option through which we can locate the exact
point where the problem occured. Because “Segmentation Fault” will appear due to several reasons
and the worst part is it will never reveal the place of errors. Step by Step process in GDB helps
us to identity the errors.

Lets quickly get into the business. here are the steps through which we can find errors using gdb.

1. Before entering into the gdb screen we need to find the process and we should attach the same to


2. For doing that , we can make use of the “ps -ef” which will list all the process which are currently
running. To get our exact process we can use grep command.

ps -ef | grep "process_name"

3. The above command will list a line in which, the second column will be the process id (usually)

4. use the following command to attach the process with GDB attach process_id(replace the process_id with the number you got from previous command)

5. once you hit enter, you can see all the dependencies(shared libraries if applicable) getting attached to GDB. Now, Gdb is ready to work.

6. The first thing we need to do , is to find the breakpoints in the file (just look for the line number where which you feel something is wrong. if you have no guess, start
from the beginnning and move step by step)

7. Once we entered into the GDB prompt everything works with the GDB command.For setting the breakpoint the command is “b”.

b HelloWorld.cpp : 10

8. The above command will set the breakpoint at line number 10 in HelloWorld.cpp

9. Now run the executable and in gdb promt give continue by hitting key “c”

10. the code runs until the breakpoint and from here you can move step by step.

11. For the next step just hit the key “n”. If you press n , it will move one line

12. To know the functions that are called from the present line, use “step” command

13. If you wanna check the values of the variable, type “print variable_name”

14. At one point you would have founded out the trouble. After that, if you need not wish to move
step by step , you can press continue . Basically , continue command will run from one breakpoint to another.

15. Once done type “quit” to come out of GDB


Comments are closed.