简体   繁体   中英

Where are local stack variables stored in C?

I have the following program in C:

1  #include<stdio.h>
2  
3  int main(void) {
4      int i=0;
5      for (int k=0; k<10; k++)
6          printf("Number: %d", k);
7      printf("Hello\n");
8      return 0;
9  }

When I run it in gdb it gives me a listing of all the registers, but I don't see the variable k in any of those reigsters. For example, in the below screenshot, I know k=4 , but I don't see that value in any of the registers. Where would this number be stored then?

在此处输入图像描述

I know k=4, but I don't see that value in any of the registers. Where would this number be stored then?

If you optimized the program, the value would indeed likely be stored in a register (but the program will be much harder to debug).

Without optimization, the value is stored on stack (to be precise, given the disassembly, it is stored at location $rbp-8 ), and is loaded into a register by the very next instruction (the one before which you have stopped).

If you do stepi and look at the value of $rax , you will find it right there.

PS info locals will give you info about local variables.

Update:

What does stepi do?

It executes a single machine instruction, then stops. You can find this out by reading the manual, or by using help stepi GDB command.

What/were is $rbp-8? Could you please explain a bit more about what that is and how it works?

That is something that would be covered in every introductory x86 programming book or tutorial.

Briefly, current state of the program execution can be described as a series of linked activation records or "frames". On x86 without optimization, the $RBP register is usually used as a frame pointer register (ie it points to the current frame). Locals are stored at negative offsets from the frame pointer (here, k is stored at offset -8).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM