Reputation: 1040
I'm trying to read the location of a variable in memory at runtime, using gdb within Eclipse, but can't really see which one is the correct address. Here is the output of gdb when I disassembly my program:
main():
0000000000400634: push %rbp
0000000000400635: mov %rsp,%rbp
5 int i = 7;
0000000000400638: movl $0x7,-0x4(%rbp)
6 int j = 8;
000000000040063f: movl $0x8,-0x8(%rbp)
8 return 0;
0000000000400646: mov $0x0,%eax
9 }
and what I want is the location of the variable i at runtime. I'm guessing it's -0x4(%rbp), but then how can I figure out what address that is?
Should I take the current value of rbp and subtract 4 from it? In this case, the value inside rbp is 0x7fffffffe250. Thus, would the location of i in memory at runtime be 0x7fffffffe250 - 0x4? Or is it just 0x7fffffffe250?
Upvotes: 0
Views: 316
Reputation:
Your guess is correct: taking the value of %ebp
within that function and subtracting 4 gives the address that i
is being stored at. This address is not predictable, though, as it depends on the position of the stack at runtime.
Moreover, you should keep in mind that not all variables will have a fixed location, either in memory or in a register -- the compiler may end up moving a value between multiple locations, or optimize an intermediate value out entirely if it's unnecessary.
Upvotes: 1