Programming in C

(Barry) #1

400 Chapter 18 Debugging Programs


Lines from a function can be listed by specifying the function’s name to the listcom-
mand:
(gdb) list foo Display lines for function foo
If the function is in another source file,gdbautomatically switches to that file.You can
find the name of the current source file being displayed with gdbby typing in the com-
mand info source.
Typing a +after the listcommand causes the next 10 lines from the current file to
be displayed, which is the same action that occurs if just listis typed.Typing a –causes
the previous 10 lines to be displayed. Both the +and –options can also be followed by a
number to specify a relative offset to be added or subtracted from the current line.

Controlling Program Execution


Displaying lines from a file doesn’t modify the way a program is executed.You must use
other commands for that.You’ve seen two commands that control the execution of a
program in gdb:run, which runs the program from the beginning, and quit, which ter-
minates execution of the current program.
The runcommand can be followed by command-line arguments and/or redirection
(<or >), and gdbhandles them properly. Subsequent use of the runcommand without
any arguments reuses the previous arguments and redirection.You can display the current
arguments with the command show args.

Inserting Breakpoints
The breakcommand can be used to set breakpointsin your program. A breakpoint is just
as its name implies—a point in your program that, when reached during execution, caus-
es the program to “break” or pause.The program’s execution is suspended, which allows
you to do things such as look at variables and determine precisely what’s going on at the
point.
A breakpoint can be set at any line in your program by simply specifying the line
number to the command. If you specify a line number but no function or filename, the
breakpoint is set on that line in the current file; if you specify a function, the breakpoint
is set on the first executable line in that function.
(gdb) break 12 Set breakpoint on line 12
Breakpoint 1 at 0x1da4: file mod1.c, line 12.
(gdb) break main Set breakpoint at start of main
Breakpoint 2 at 0x1d6c: file mod1.c, line 3.
(gdb) break mod2.c:foo Breakpoint in function foo in file mod2.c
Breakpoint 3 at 0x1dd8: file mod2.c, line 4.
When a breakpoint is reached during program execution,gdbsuspends execution of your
program, returns control to you, and identifies the breakpoint and the line of your pro-
gram at which it stopped.You can do anything you want at that point:You can display or
set variables, set or unset breakpoints, and so on.To resume execution of the program, you
can simply use the continuecommand, which can be abbreviated as simply c.
Free download pdf