5.5 Modifying variables
To temporarily fix the null pointer bug discovered above, we can change
the value of p
in the running program using the set
variable
command.
Variables can be set to a specific value, or to the result of an
expression, which may include function calls. This powerful feature
allows functions in a program to be tested interactively through the
debugger.
In this case we will interactively allocate some memory for the pointer
p
using the function malloc
, storing the value 255 in the
resulting location:
(gdb) set variable p = malloc(sizeof(int))
(gdb) print p
$2 = (int *) 0x40013f98 (address allocated by malloc
)
(gdb) set variable *p = 255
(gdb) print *p
$3 = 255
If we now continue stepping through the program with the new value of
p
the previous segmentation fault will not occur:
(gdb) step
foo (p=0x40013f98) at null.c:13
13 int y = *p;
(gdb) step
14 return y;