GDB Usage Example
The objective of this appendix is to illustrate on a very simple case how to use
gdb(orlldb) to debug a program.
Using gdb
- Once the program is written, it must be compiled with the
-goption (to includedebuginformation). - Launch the debugger with our program as an argument (by default
a.out). - Start program execution via
run(orr). - Identify bugs or errors
- Quit the program via
quit(orq)
How to Identify Errors
In general, the program executes until it reaches:
- its termination
- an error
- a breakpoint
- an interrupt (
CTRL+C)
Breakpoints
- Set:
break line_numberorbreak function_name(b) (multiple breakpoints can be defined) - Delete:
delete breakpoint_number - List breakpoints:
info break - Delete all breakpoints:
delete(d) - Disable:
disable xordisable x-y - Enable:
enable xorenable x-y, optionally addoncefor a single activation - Stop on condition:
break x if condition - Watch:
watch variableorwatch expr - Resume:
continue(c) resumes until the next breakpoint/error/terminationnext(n) executes the next instruction/function and pausesstep(s) executes the next instruction and pausesfinish: goes directly to the end of the current function- It is possible to use
step xornext xto advancexlines at once. - It is possible to use
continue xto skip the current breakpointxtimes (useful for loops). - Pressing Enter repeats the last command
Displaying Variables
- To display a local/global variable:
print expr(p expr) - classic operators work (
[],&,*) - It is possible to format the display:
p/xp/dp/up/op/cp/fp/ato get results in decimal, octal, hexadecimal…
Call Stack
- Inspect the stack
btorbt full - Navigate the stack
up/down
Going Further
You can consult the following link https://www.rocq.inria.fr/secret/Anne.Canteaut/COURS_C/gdb.html which contains additional commands.
Practical Application
This is a program that contains several errors (uninitialized variable, passing a value instead of a pointer). We will illustrate how to use gdb to find these errors.
Example Program
exemple_gdb_init.c
#include <stdio.h>
int somme (int n)
{
int result = 0;
for (unsigned int i = 0; i < n; i++)
{
result += i;
}
return result;
}
void get_from_user (int n)
{
do
{
printf ("Entrer un entier (>= 0)\n");
scanf ("%d", &n);
} while (n < 0);
}
int main ()
{
int value;
get_from_user (value);
printf ("Somme = %d\n", somme (value));
return 0;
}