next up previous contents index

[ENGN3213 Home]

Local Variables and Stack Frames

    Many subroutines uses local variables for temporary use. By static allocation, we mean that fixed memoy locations are reserved for the variables. However, a subroutine may be called in a re-enterant or recursive way, and so static allocation is not generally suitable since several instances of the subroutine will be useing the same memory for the variables. In such cases dynamic allocation of storage is preferable, since new memory space is allocated each time the subroutine is called.

The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.

The 68000 has two special instructions for creating and removing stack frames: LINK and UNLK. As we shall see, C compilers uses these instructions for dynamic memory allocation. The LINK and UNLNK instructions operate as follows (see Figure 110):

LINK: $ (SP) \longleftarrow (SP)-4$
  $((SP)) \longleftarrow \ (A6)$
  $ (A6) \ \longleftarrow \ (SP)$
  $ (SP) \longleftarrow (SP)-d$
UNLK: $ (SP) \ \longleftarrow \ (A6)$
  $ (A6) \ \longleftarrow \ ((SP))$
  $ (SP) \longleftarrow (SP)+4$


  
Figure 110: Stack frame before and after the LINK instruction.
\begin{figure}
\begin{center}
\epsfig{file=images/stack-fr-1.eps}\end{center}\end{figure}

An example of the use of stack frames is given in the code clab64s.s from CLAB6. Figure 111 illustrates the use of the stack in that code (this includes stack frame, parameter passing and temporary saving of working registers). Here, the stack frame consists of 2 bytes, for a 1 word local variable.


  
Figure 111: Stack use in clab64s.s.
\begin{figure}
\begin{center}
\epsfig{file=images/stack-fr-2.eps}\end{center}\end{figure}


next up previous contents index

[ENGN3213 Home]

ANU Engineering - ENGN3213