Programming in C

(Barry) #1

398 Chapter 18 Debugging Programs


Oops! That’s not good.You have only five elements in the array and you tried to access
the 233rd element when the error occurred. On your system, the error might occur ear-
lier or later. But eventually, you should get an error.
Before you exit from gdb, look at another variable. See how nicely gdbdeals with
variables like arrays and structures:
(gdb) print data Show the contents of the data array
$3 = {1, 2, 3, 4, 5}
(gdb) print data[0] Show the value of the first element
$4 = 1
You’ll see an example of a structure a little later.To complete this first example with gdb,
you need to learn how to get out.You can do that with the quitcommand:
(gdb) quit
The program is running. Exit anyway? (y or n) y
$
Even though the program had an error, technically speaking, it was still active inside gdb;
the error merely caused your program’s execution to be suspended, but not terminated.
That’s the reason gdbasked for confirmation about quitting.

Working with Variables


gdbhas two basic commands that allow you to work with variables in your program.
One you’ve seen already is print.The other allows you to set the value of a variable.
This is done with the set varcommand.The setcommand actually takes a number of
different options, but varis the one you want to use to assign a value to a variable:
(gdb) set var i=5
(gdb) print i
$1 = 5
(gdb) set var i=i*2 You can write any valid expression
(gdb) print i
$2 = 10
(gdb) set var i=$1+20 You can use so-called "convenience variables"
(gdb) print i
$3 = 25
A variable must be accessible by the current function, and the process must be active, that
is, running.gdbmaintains an idea of a current line (like an editor), a current file (the
source file of the program), and a current function.When gdbstarts up without a core
file, the current function is main, the current file is the one that contains main, and the
current line is the first executable line in main; otherwise, the current line, file, and pro-
cedure are set to the location where the program aborted.
If a local variable with the specified name doesn’t exist,gdblooks for an external
variable of the same name. In the previous example, the function executing at the time
the invalid access occurred was main,and iwas a variable local to main.
Free download pdf