GDB: Variables

By default, GDB prints a value according to its data type. However, we can change the output format.

print [[OPTION]... --] [/FMT] [EXP]

FMT, format:

int main()
{
  int n = 0x01020304;
  char* str = "hello";
}
(gdb) print n
$1 = 16909060
(gdb) print/x n
$2 = 0x1020304
(gdb) print/a &n
$4 = 0xffffffffec9c


(gdb) print str
$1 = 0x4006c0 "hello"
(gdb) print *str@6
$2 = "hello"
(gdb) print/c *str@6
$3 = {104 'h', 101 'e', 108 'l', 108 'l', 111 'o', 0 '\000'}
(gdb) print/x *str@6
$4 = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x0}


Automatic Display

Automatic display variables each time the program stops.

int main()
{
  int i = 0, sum = 0;
  while (i < 3)
  {
    sum += i;
    i += 1;
  }
}
(gdb) set print frame-info location
(gdb) break 7

(gdb) display i
(gdb) display sum

(gdb) while 1
 >continue
 >end
Breakpoint 1, main (argc=1, argv=0xffffffffee18) at demo.c:7
1: i = 0
2: sum = 0

Breakpoint 1, main (argc=1, argv=0xffffffffee18) at demo.c:7
1: i = 1
2: sum = 1

Breakpoint 1, main (argc=1, argv=0xffffffffee18) at demo.c:7
1: i = 2
2: sum = 3


Examine Memory

The command x is used to examine memory.

    x/nuf addr
short n = 0x0102;

(gdb) x/1wd &n
0xffffffffec9c: 258
(gdb) x/1wx &n
0xffffffffec9c: 0x01020
(gdb) x/4bx &n
0xffffffffec9c: 0x02    0x01


Convenience Variables

GDB provides convenience variables that can hold on to a value and read later.

set $variable = value
show convenience
int n = 16909060;

(gdb) set $var1 = n
(gdb) print $var
$15 = 16909060


Environment Variables

show environment [varname]
set environment varname [=value]
unset environment varname