15.3.2 Local Variables

As it turns out local variables are also stack items! Unlike parameters, which must be created by the caller, local variables are created by the called subroutine. Most compilers use the convention of ``local variables are on the other side of the frame pointer.'' This means local variables are reserved on the stack after %ebp is saved.

Let us resume our example from the previous section. We add the following local variables:

These local variables will, then, have the following symbolic definitions:

  strBuffer = oldbp-32 # offset from %ebp to strBuffer
  strPtr = strBuffer-4 # offset from %ebp to strPtr
  cmpChar = strPtr - 2 # offset from %ebp to cmpChar
      

Unless these local variables should be initialized, the allocation is a simple addl instruction. Let's look at the complete entry code of the subroutine:

sub1:
      pushl  %ebp  # save the old value of ebp
      movl   %esp,%ebp # initialize this frame
      addl   $cmpChar,%esp # adjust stack pointer to reserve for local var
      

Note that addl is used instead of subl because cmpChar is already a negative value.

To clean up the stack right before this subroutine returns, we need the following code:

      movl   %ebp,%esp # deallocate local var
      popl   %ebp # restore old value of ebp
      ret    # time to return

Copyright © 2009-04-16 by Tak Auyeung