问题
I am trying to understand the process of declaration and assignment of a primitive type at the back stage.
int i;i = 3;
For 1), on the memory stack, it assigns a space for storing an int type value named i For 2), it assigns the value 3 to the space preserved above
Is there a memory address there? From my impression, memory address is always associated with the objects on the heap?
Update:
Regarding the replies:
So, for every variable on the stack, they are all assigned a memory address as well just like the objects on the heap. Am I correct?
But for Java, this is not the case?
回答1:
There are not always addresses involved. The compiler can put variables into registers if it finds that their address is never taken by the programmer. So you wouldn't need any access to the main memory. For example in your code above, what the compiler could generate could be as simple as
add $2, $0, 3
to put value 3 into register 2. As soon as you create a pointer and make it point to that variable, then you have an address, actually. And then the variable cannot be in a register only anymore.
回答2:
Assuming you're talking about C or C++ (I can't tell), yes. You can access the address like so:
int i = 3;
int *k = &i; // k now is a pointer to i
*k = 4; // assigns the value k points to (i) to 4, i is now 4
回答3:
How else do stack buffer overflows occur? :) someone's got to be writing to a pointer to the stack.
回答4:
Really stack is special area of proccess virtual memory, so everything in stack has memory addres. Head of the stack holded by ESP (SP) registry (x86 architecture). Stack addresses usualy lower than memory adresses, because stack located closer to begining of proccess vitrual memory then heap.
来源:https://stackoverflow.com/questions/316194/is-primitive-assigned-a-memory-address