GDB's Own Variables

In addition to the variables you declare in your program, GDB also provides mechanisms for others.

Output values from GDB's print command are labeled $1, $2, and so on, with these quantities collectively being called the value history. They can be used to produce shortcuts in future print commands that you issue.

For instance, consider the bintree example from Our Main Example Code. Part of a GDB session might look like this:

(gdb) p tmp->left
$1 = (struct node *) 0x80496a8
(gdb) p *(tmp->left)
$2 = {val = 5, left = 0x0, right = 0x0}
(gdb) p *$1
$3 = {val = 5, left = 0x0, right = 0x0}

What happened here is that after we printed out the value of the pointer tmp->left and found it to be nonzero, we decided to print out what this pointer pointed to. We did so twice, first the conventional way, and then via the value history.

In that third printing, we referred to $1 in the value history. If we had not done the conventional printing, we could have made use of the special value history variable $:

(gdb) p tmp->left
$1 = (struct node *) 0x80496a8
(gdb) p *$
$2 = {val = 5, left = 0x0, right = 0x0}

Say you have a pointer variable p which at different times points to different nodes in a linked list. During your debugging session, you may wish to record the address of a particular node, say because you wish to recheck the value in the node at various times during the debugging process. The first time p gets to that node, you could do something like

(gdb) set $q = p

and from then on do things like

(gdb) p *$q

The variable $q here is called a convenience variable.

Convenience variables can change values according to C rules. For example, consider the code

int w[4] = {12,5,8,29};

main()

{
   w[2] = 88;
}

In GDB you might do something like

Breakpoint 1, main () at cv.c:7
7          w[2] = 88;
(gdb) n
8       }
(gdb) set $i = 0
(gdb) p w[$i++]
$1 = 12
(gdb)
$2 = 5
(gdb)
$3 = 88
(gdb)
$4 = 29

To understand what happened here, recall that if we simply hit the ENTER key in GDB without issuing a command, GDB takes this as a request to repeat the last command. In the GDB session above, you kept hitting the ENTER key, which meant you were asking GDB to repeat the command

(gdb) p w[$i++]

That meant not only that a value would be printed, but also that the convenience variable $i would increment.