3

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!

5

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)

2

The C language standard does not mandate how memory gets allocated for function parameters, only how that memory should behave. It only specifies that function parameters have block scope (not visible outside the function body), no linkage (no other identifiers in the code refer to the same object), and automatic storage duration (space is allocated at the beginning of the function and released when the function exits).

The exact memory allocation behavior is a function of the specific platform's1 calling conventions. For example, on x86-64, space will not be allocated on the stack for the function argument; instead, it will be passed via a register (%rcx on Windows, %rdi on *nix). Many RISC architectures (MIPS, PowerPC, SPARC) also pass arguments via registers rather than the stack for simple calls.

Furthermore, depending on the platform, stack space may need to be aligned on specific boundaries; if you pass a single 2-byte argument via the stack, but the stack pointer must be aligned on 4-byte addresses, then the stack pointer will be adjusted by 4 bytes, leaving 2 bytes allocated but unused.


  1. Where "plaform" is the combination of hardware and operating system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy