Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local initial values are stored at?

Tags:

c

segments

#include <stdio.h>  
int main()
{
  int i = 10;
  return 0;
}

In the above program, where exactly the value 10 is stored ?

I understand the variable i is stored in the stack. stack is populated during run time. From "where exactly" 10 is coming from.

like image 908
kumar Avatar asked Dec 06 '22 08:12

kumar


2 Answers

10 is a constant, so the compiler will use the number 10 directly in the executable part of your program as part of the CPU instructions.

Here's the assembly produced on my system with gcc:

movl    $10, -4(%rbp)

(The 4 is because an int is 4 bytes long)

Note that all of these things are part of the implementation, but the above happens in practice. The language itself doesn't specify these details.

like image 126
teppic Avatar answered Dec 08 '22 20:12

teppic


10 is a "literal", which will be generated by the compiler during compilation. And then it will be assigned to your variable on the stack. Like

mov eax, 10;
mov [0x12345678], eax;

This is pseude-code, though, but will assign your variable i (address is here 0x12345678) the value 10, previously stored in eax.

like image 33
bash.d Avatar answered Dec 08 '22 21:12

bash.d