CSc 520 - Principles of Programming Languages
4 : Memory Management -- Introduction

Christian Collberg

Department of Computer Science

University of Arizona

1 Memory Management

2 Memory Management...

3 Memory Management...

 
  • Static allocation - Global variables
  • Stack allocation - Procedure call chains, Local variables.
  • Dynamic allocation - NEW, malloc, On the heap.
MemoryLayout

4 Dynamic Memory Management

Pascal, C, C++, Modula-2
Explicit deallocation of dynamic memory only. I.e. the programmer is required to keep track of all allocated memory and when it's safe to free it.
Eiffel
Implicit deallocation only. Dynamic memory which is no longer used is recycled by the garbage collector.
Ada
Implicit or explicit deallocation (implementation defined).
Modula-3
Implicit and explicit deallocation (programmer's choice).

5 Run-Time Memory Organization

  Low $\Rightarrow$ Heap
  Addresses $\Downarrow$
  ...
  $\Uparrow$
  Stack
  Static Data
  High Initialized Data
  Addresses $\Rightarrow$ Text Segment

6 Run-Time Memory Organization...

7 Storage Allocation

Global Variables
are stored in the Static Data area.
Strings
(such as "Bart!") are stored in the Initialized Data section.
Dynamic Variables
are stored on the Heap:
\begin{gprogram}
PROCEDURE P ();\\
\x VAR X : POINTER TO CHAR; \\
BEGIN \\
\xx NEW(X); \\
END P
\end{gprogram}

8 Storage Allocation...

Own Variables
are stored in the Static Data area. An Own variable can only be referenced from within the procedure in which it is declared. It retains its value between procedure calls.
\begin{gprogram}
PROCEDURE P (X : INTEGER);\\
\x OWN W : INTEGER; \\
\x VAR L : INTEGER; \\
BEGIN W := W + X; END P
\end{gprogram}

9 Global Variables - MIPS

Running Example:
\begin{gprogram}
PROGRAM P; \\
\x VAR X : INTEGER; \xxxxxx (* 4 bytes. *)\\
\x...
...(* 1 byte. *)\\
\x VAR R : REAL; \xxxxxx (* 4 bytes. *) \\
END.
\end{gprogram}

10 Global Variables - Allocation by Name


\begin{gprogram}
\xxx .data\\
\_X:\xxx .space 4 \\
\_C:\xxx .space 1 \\
\xxx ...
...ary.\\
\_R:\xxx .space 4 \\
\xxx .text\\
main:\xxx lw \$2, \_X
\end{gprogram}

11 Global Variables - Allocation in Block


\begin{gprogram}
\xxx .data\\
\_Data:\xxx .space 48 \\
\xxx .text\\
main:\xxx...
...xxxx \char93  C\\
\xxx l.s \xx \$f4, \_Data+8 \xxxxx \char93  R
\end{gprogram}

12 Global Variables - Allocation on Stack


\begin{gprogram}
main:\xxx subu \$sp,\$sp,48 \\
\xxx move \$gp,\$sp \\
\xxx l...
...xxxxx \char93  C\\
\xxx l.s \xx \$f4, 8(\$gp) \xxxxx \char93  R
\end{gprogram}

_X: .space 4
Each access lw $2, _X takes 2 cycles.
_Data: .space 48
Each access lw $2, _Data+32 takes 2 cycles.
subu $sp,$sp,48
1 cycle to access the first 64K global variables.

13 Storage Allocation...

Local Variables:
stored on the run-time stack.
Actual parameters:
stored on the stack or in special argument registers.

14 Readings and References



Christian Collberg 2008-01-30