c - Same address for static variable but different for local variable -
i trying learn operating systems. @ present in virtual addressing. book says if have 1 static variable
, 1 local variable
, update them , sleep time , try print addresses across multiple such processes running 1 same memory address.
this because each process feel has whole memory , has no control of physical memory address remain same among various process running @ same time. understand when run program getting same address across static variables different across local variables. little operating systems knowledge not able understand why happening. code
int staticvar = 0; int main(int argc, char const *argv[]) { int localvar = 0; staticvar += 1; localvar += 1; sleep(10); printf("static address: %x, value: %d\n", &staticvar, staticvar ); printf("static address: %x, value: %d\n", &localvar, localvar ); return 0; }
this output when run 3 different processes simultaneously.
./a.out static address: 60104c, value: 1 static address: 67c6128c, value: 1 ./a.out static address: 60104c, value: 1 static address: 89e2c11c, value: 1 ./a.out static address: 60104c, value: 1 static address: 226e03dc, value: 1
local variables allocated on stack frame of function called. stack frame referenced through stack pointer (sp) register initialized os upon start of process. program uses sp dynamically allocate stack space , values stored there. type of access prepared use dynamic address, , knowing that, os can choose initialize process' stack frame wherever sees fit best in current context.
"static" variables, on other hand, referenced constant addresses compiled (assembler) code. that's why must reside @ known-at-compile-time location.
edit:
as noted, value of sp changes through program execution, depending on stack usage. therefore, if call same funtion different parts of program, address of local variable may different each time.
Comments
Post a Comment