How can I print all global variables/local variables? Is that possible in gdb?
4 Answers
Type info variables to list "All global and static variable names" (huge list.
Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.
Type info args to list "Arguments of the current stack frame" (names and values).
10 Comments
info variables should be static variables within that compile unit,right?y is renamed to y.1913 on compilation.y in function foo and another y in bar. To distinguish them, a different name must be assigned to the two y's.In case you want to see the local variables of a calling function use select-frame before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
1 Comment
select-frame can be abbreviated as sel. Alternatively use frame/f, which also print the frame)In addition, since info locals does not display the arguments to the function you're in, use
(gdb) info args
For example:
int main(int argc, char *argv[]) {
argc = 6*7; //Break here.
return 0;
}
argc and argv won't be shown by info locals. The message will be "No locals."
Reference: info locals command.
Comments
sometimes a variable may be <optimized out>. For example:
(gdb) info locals
a = <optimized out>
b = 846930886
this can be seen in the below program
#include <cstdio>
#include <cstdlib>
int main() {
int a = rand();
std::printf("%d\n", a);
std::printf("%d\n", a);
std::printf("%d\n", a);
int b = rand();
std::printf("%d\n", b);
std::printf("%d\n", b);
}
// compile with `g++ -O2 -g a.cpp`
while if the variable really cannot be found then nothing you can do, but at least you can see where the program store(d) the variable at, for this you can use info address. For example
(gdb) info address a
Symbol "a" is multi-location:
Base address 0x1162 Range 0x555555555162-0x555555555166: a variable in $rax
Range 0x555555555166-0x55555555516a: a variable in $rdx
Range 0x55555555516a-0x55555555519f: a variable in $r12
.
(gdb) p $rip
$9 = (void (*)(void)) 0x5555555551a8 <main()+104>
as you can see, 0x5555555551a8 is past the range that a stays alive, so you cannot obtain its value.
In addition, if you e.g. use rr (see How to go to the previous line in GDB?), you can do an appropriate amount of reverse-step or reverse-stepi until the variable is in scope.