MSilver
MSilver

Reputation: 15

Variables on heap and stack

I've been trying to look for the answer to this question, but its a little tricky to me.

So it goes!

    int square(int* a){
      return (*a)*(*a)
    }


    int main(){
      int b = 20;  
      square(&b);
    }

My question is: Where are stored variables a and b?

In my opinion variable b is stored in stack but i have some questions regarding a.

When you call square(&b) you're passing the reference, in this case de address of variable b in the stack.

Then, function square(int* a) receives a (int* a) argument which means that it will receive a pointer which in this case is the reference for variable b in the stack. So the value for variable a will be the address of the variable b. But both will be stored in stack. I am pretty sure that's on the stack, but...Or will b in the stack and a in the heap? Thanks by the way.

Upvotes: 0

Views: 149

Answers (2)

pylua
pylua

Reputation: 635

You are correct! b will be pushed onto the stack, and a is just a pointer to b, so the reference of b and the value held by the pointer a are the same value, which is the stack location of b. However, the pointer 'a' will not stay on the stack after the function is called-- it will go out of scope, but 'b' will still be on the stack after the function is called, though its value will be changed.

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41180

The value b will be on the stack.

When square is called, a and &b are the same value. Depending on the calling convention and compiler optimizations, this value may be in a register, or on the stack, or both.

Upvotes: 2

Related Questions