views:

66

answers:

2

When we call a function (let say with 3 parameters), how are the variables are stored in the stack memory.

+4  A: 

It is entirely implementation-dependent how arguments are passed to a function.

Function arguments might not even be passed on the stack; they could be passed in registers, for example.

You will need to look up information for your specific platform to determine how arguments are passed. Wikipedia has a whole page dedicated to the various x86 calling conventions.

James McNellis
Yes, on sparc first six args are in registers, but then there is that register window spill ...
Nikolai N Fetissov
+1  A: 

When arguments are pushed onto the stack, C does that from right to left. However, depending upon both the architecture and the number of parameters, it is possible that the stack will not be used (or only partly used) and registers would be used instead.

For the sake of argument, let us say that we are dealing with the x86 architecture (32-bit). The stack frame will look like ...

(Stack grows down.  High stack address is here)
arg3
arg2
arg1
ret addr         <--- Auto pushed by 'call'
old base ptr     <--- Called function typically saves the old base ptr
...              <--- Carve space for local variables
(Low stack address is here.)

Continuing with the above example, the called function can access the parameters using the following ...

movl  8(%ebp), %eax    // move arg1 into EAX
movl  12(%ebp), %edx   // move arg2 into EDX

and so on.

If I remember correctly, PowerPC has something like eight (8) registers available for passing parameters--r3...r10 inclusive. As for other architectures, you'll have to look them up.

Hope this helps.

Sparky
"C does that from right to left," is implementation specific. It describes the `cdecl` calling convention commonly used by C implementations on the x86. An implementation is free to push parameters left to right or in any other order.
James McNellis