gcc [flags] <source files> -o <output file>
gcc hi.c -o hi.x
-g
option to enable built-in debugging support (which gdb needs)gcc -g hi.c -o hi.x
The example used:
gcc -Wall -Werror -std=c89 -pedantic-errors -g hi.c -o hi.x
but I wasn't good enough at writing sneaky segfaults to get anything through that.
gdb
or gdb hi.x
You’ll get a prompt that looks like this:(gdb)
(gdb) file hi.x
hi.x
is the program you want to load, and file
is the command to load it.help
command, with or without an argument:(gdb) help [command]
int *add_ptr(int *a, int *b)
{
int val = *a + *b ;
return &val ;
}
int main()
{
int a = 2, b = 3, *ptr ;
ptr = add_ptr(&a, &b) ;
printf("Sum = %d\n", *ptr) ;
return 0;
}
(gdb) run
0x00005555555551fc in main () at hi.c:16
16 printf("Sum = %d\n", *ptr) ;
break
(gdb) break hi.c:15
int *add_ptr(int *a, int *b) ;
(gdb) break add_ptr
run
command again. This time, it should stop where you tell it to (unless a fatal error occurs before reaching that point).continue
run
again would restart the program from the beginning, which isn’t always very useful.step
This gives you really fine-grained control over how the program proceeds. You can do this a lot...step
the command next
single-steps as well, except this one doesn’t execute each line of a sub-routine, it just treats it as one instruction.step
or next
a lot of times can be tedious. If you just press ENTER, gdb will repeat the same command you just gave it. You can do this a bunch of times.print
command prints the value of the variable specified, and print/x
prints the value in hexadecimal:Breakpoint 1, add_ptr (a=0x7fffffffdd88, b=0x7fffffffdd8c) at hi.c:7
7 {
(gdb) print/x a
$3 = 0x7fffffffdd88
(gdb) watch val
val
is modified, the program will interrupt and print out the old and new values.val
to watch if there is more than one declared in your program.
backtrace
- produces a stack trace of the function calls that lead to a seg fault (should remind you of Java exceptions)where
- same as backtrace
- you can think of this version as working even when you’re still in the middle of the programfinish
- runs until the current function is finisheddelete
- deletes a specified breakpointinfo breakpoints
- shows information about all declared breakpointshelp
break
command as before:(gdb) break file1.c:6 if i >= ARRAYSIZE
i
is greater than or equal to the size of the array (which probably is bad if line 6 does something like arr[i]
Conditional breakpoints can most likely avoid all the unnecessary stepping, etc.struct entry { int key; char *name; float price; long serial_number; };
struct entry * e1 = <something>;
(gdb) print e1
(gdb) print e1->key
(gdb) print e1->name
(gdb) print e1->price
(gdb) print e1->serial number
(gdb) print (*e1).key
(gdb) print (*e1).name
(gdb) print (*e1).price
(gdb) print (*e1).serial number
(gdb) print *e1
(gdb) print list prt->next->next->next->data