In order to use gdb to debug a C program, you should compile your C program with -g option. It allows the compiler to collect the debugging information. For example,
gcc –g –o test test.c
where gcc is the compiler, test.c is the C program and test is the executable file.
Suppose we need to debug the executable file, the followings are basic steps for debugging a c program using gdb debugger:
Step 2: Set up a break point inside C program
Syntax: break <line_number>
Note that since now on, you execute the commands in the gdb command line, not in the bash command line.
Step 3: Execute the C program in gdb debugger
where args is the command line arguments you pass to the program.
Afterwards, you can use various gdb commands to examine executing Code. Example options of examining executing Code include:
p or print: Print the content of variables or parameters.
x or examine: Examine memory contents in different forms, including binary and hexadecimal forms. It uses the following syntax:
where NUM is the number of objects to display, SIZE is the size of each object (b = byte, h = half-word, w = word, g = giant word (eight bytes)), FORMAT indicates how to display each object (d = decimal, x = hex, o = octal, t = binary), and [Address] is the memory address. For example,
the following x command will display a program’s variable a’s actual value in hex form when given the argument &a. 4 is the repeat count or the number of units whose size is specified by argument b, which stands for byte as the unit size. ‘x’ means that you want to display or output the value in hexadecimal form, which is the default display format for the x command.
(gdb) x/4bx &a
0xbffff56c: 0x10 0x00 0x00 0x00
Step 4: Continue, stepping over and in after a breakpoint
There are three kinds of gdp operations after a breakpoint:
c or continue: Execution will continue until the next breakpoint in your code.
n or next: Executing the next line of code after the current breakpoint.
s or step: The s command is very similar to the n command, except for that the s command steps into a function and executes it line by line, whereas the n command simply treats a function call as one line of code.
Step 5: Quit from the gdb debugger