tags:

views:

195

answers:

5

I am trying to understand the process of declaration and assignment of a primitive type at the back stage.

1) int i;

2) 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 memory address there? From my impression, memory address is always associated with the objects on the heap?

Thanks!

+1  A: 

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
Kyle Cronin
A: 

How else do stack buffer overflows occur? :) someone's got to be writing to a pointer to the stack.

Jimmy
A: 

Thank you for so quick reply!

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?

Thx again.

Yes and no. Stack variables "go away" once they go out of scope, put heap variables which are allocated with stuff like malloc() or "new" stick around until you deallocate them.
Dave Markle
They get deallocated automatically, but they still have an address, always. The only things that don't have addresses are bitfields in structs.
Martin v. Löwis
A: 

But for Java, this is not the case?

Afraid not - every Java object is allocated on the heap and has an implicit pointer, but the Java primitives (int, char, bool, etc) do not.
Kyle Cronin
+1  A: 

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.

Johannes Schaub - litb