Pointers And Memory - Contents
A D V E R T I S E M E N T
You do not need to know how local variables are implemented during a function call, but
here is a rough outline of the steps if you are curious. The exact details of the
implementation are language and compiler specific. However, the basic structure below is
approximates the method used by many different systems and languages...
To call a function such as foo(6, x+1)...
- Evaluate the actual parameter expressions, such as the x+1, in the caller's
context.
- Allocate memory for foo()'s locals by pushing a suitable "local block" of
memory onto a runtime "call stack" dedicated to this purpose. For
parameters but not local variables, store the values from step (1) into the
appropriate slot in foo()'s local block.
- Store the caller's current address of execution (its "return address") and
switch execution to foo().
- foo() executes with its local block conveniently available at the end of the
call stack.
- When foo() is finished, it exits by popping its locals off the stack and
"returns" to the caller using the previously stored return address. Now the
caller's locals are on the end of the stack and it can resume executing.
For the extremely curious, here are other miscellaneous notes on the function call
process...
- This is why infinite recursion results in a "Stack Overflow Error" � the
code keeps calling and calling resulting in steps (1) (2) (3), (1) (2) (3), but
never a step (4)....eventually the call stack runs out of memory.
- This is why local variables have random initial values � step (2) just
pushes the whole local block in one operation. Each local gets its own area
of memory, but the memory will contain whatever the most recent tenant
left there. To clear all of the local block for each function call would be
too time expensive.
- The "local block" is also known as the function's "activation record" or
"stack frame". The entire block can be pushed onto the stack (step 2), in a
single CPU operation � it is a very fast operation.
- For a multithreaded environment, each thread gets its own call stack
instead of just having single, global call stack.
- For performance reasons, some languages pass some parameters through
registers and others through the stack, so the overall process is complex.
However, the apparent the lifetime of the variables will always follow the
"stack" model presented here.
Back to Table of Contents
A D V E R T I S E M E N T
|
Subscribe to SourceCodesWorld - Techies Talk |
|