Memory Allocation in C During Function Calls

cmemory usage

I have a really basic question regarding how memory gets allocated in a code written in C.

Let's say that I have something like this:

int pointless(int a); 
int main(){
     int num1,num2;
     num1=1;
     num2=pointless(num1);
     return 0;
}
int pointless(int a)
{             
     return a;
}

What I would like to know is what is happening inside the pointless() function. In main() we have already allocated two bytes for the "num1" variable, which gets passed on to the called function. At this point, when I jump into the pointless function, will it allocate the space once more – now for the "a" variable – or will it simply somehow only allow the function to access the value of the variable in the memory? (I am going to get problems with what I am writing now if temporarily there's a duplicate allocation for the variables while we're inside the pointless() function.)

Thanks!

Best Answer

It's going to allocate the space for the int on the stack, copy the value of 'num1' onto the stack, call the method and then return the value, at which point the stack is popped. Essentially you'll have a copy of 'num1' on the stack for your function to use.

If you passed a pointer or a reference to 'num1' instead, then the address would be put on the stack, and your function would amend the variable via that address. So you wouldn't have a value copy but rather a reference to the original variable.

Here's a useful description of what's going on (from StackOverflow)

Related Topic