When is space allocated for local variables?
Example
function Test: Boolean;
var
a, b, c: Integer;
begin
...
end;
When a program containing such code is executed, are a
, b
, and c
allocated each time Test
is called, or are they alloc开发者_如何学JAVAated only once somewhere in the initialization phase of the execution? I ask this because such an information is not available in the debugger.
Local variables are created in the stack, after the call to the function. They are removed by the called function by default when the function returns.
Here is a more exact version.
Local variables are allocated:
- Usually on the stack;
- In registers if the optimizer can use it: for instance, a simple method with just a loop and a
var i: integer
declared as local variable will likely allocatei
as a CPU register, for better speed.
How is stack allocated?
On both x86 and x64 scheme, the compiler has the same process:
- It first computes all the space needed, at compile time;
- It generates code to reserve this space on the stack (e.g. a
MOV EBP,ESP; SUB ESP,16
); - It generates code to initialize reference-counted variables allocated on the stack (e.g.
string
) - other kind of variables (likeinteger
) have no default value, and can be any random content which is on the stack; - It generates an hidden
try..finally
block if there are some reference-counted variables; - It generates the code for the internal of the function/method;
- Now here the
finally
part of the function/method: it generates code to free all reference-counted variables; - It generates code to release the space on the stack (e.g. an
MOV ESP,EBP
); - It generates code to return to the caller function.
Most of the time, a "stack frame" (pointed by register EBP
) is created: it is used to access directly all the variables allocated on the stack.
There is a specific handling of the result
variable of a function: sometimes, it is a CPU/FPU register, sometimes, it is a variable initialized by the caller, and passed as an additional parameter.
On x64, it is a bit more complicated, since exceptions are not handled the same, and all registers need to have some space allocated on the stack, if there is an inner call.
On Mac OS, there are some alignment issues.
All this stack allocation / initialization process is the reason why for some small functions/methods, declaring them inline
will make the code faster to execute: all this stack handling is sometimes slow, if the process within the function is very simple.
For more details, see the official Delphi documentation.
精彩评论