Print addresses of all local variables in C

2.6k views Asked by At

I want to print the addresses of all the local and global variables which are being used in a function, at different points of execution of a program and store them in a file.

I am trying to use gdb for this same.

The "info local" command prints the values of all local variables. I need something to print the addresses in a similar way. Is there any built in command for it?

Edit 1

I am working on a gcc plugin which generates a points-to graph at compile time.

I want to verify if the graph generated is correct, i.e. if the pointers do actually point to the variables, which the plugin tells they should be pointing to.

We want to validate this points-to information on large programs with over thousands of lines of code. We will be validating this information using a program and not manually. There are several local and global variables in each function, therefore adding printf statements after every line of code is not possible.

2

There are 2 answers

0
Tom Tromey On BEST ANSWER

There is no built-in command to do this. There is an open feature request in gdb bugzilla to have a way to show the meaning of all the known slots in the current stack frame, but nobody has ever implemented this.

This can be done with a bit of gdb scripting. The simplest way is to use Python to iterate over the Blocks of the selected Frame. Then in each such Block, you can iterate over all the variables, and invoke info addr on the variable.

Note that printing the address with print &var will not always work. A variable does not always have an address -- but, if the variable exists, it will have a location, which is what info addr will show.

One simple way these ideas can differ is if the compiler decides to put the variable into a register. There are more complicated cases as well, though, for example the compiler can put the variable into different spots at different points in the function; or can split a local struct into its constituent parts and move them around.

By default info addr tries to print something vaguely human-readable. You can also ask it to just dump the DWARF location expressions if you need that level of detail.

0
Pandrei On

programmatically ( in C/C++ ) you use the & operator to get the address of a variable (assuming it's not a pointer):

int a; //variable declaration
print("%d", a); //print the value of the variable (as an integer)
print("0x%x", &a); //print the address of the variable (as hex)

The same goes for (gdb), just use &

plus the question has already been answered here (and not only)