CSc 520 - Principles of Programming Languages
6 : Memory Management -- Heap Allocation

Christian Collberg

Department of Computer Science

University of Arizona

1 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).

2 Interface to Dynamic allocation

C, C++:
char* malloc(size) and free(char*) are standard library routines.
Pascal:
new(pointer var) and dispose(pointer var) are builtin standard procedures.
Java:
new(class name) is a standard function.
LISP:
cons creates new cells:

ConsCell

3 Explicit Deallocation

malloc1

4 Memory Leaks


\begin{gprogram}
XX\=XX\=XX\=\kill
DEFINITION MODULE Complex; \\
\x TYPE T; \\ ...
...parrow$.Im := $\cdots$;\\
\xx RETURN x; END Add;\\
END Complex;
\end{gprogram}

5 Memory Leaks...


\begin{gprogram}
MODULE Use; \\
\x IMPORT Complex; \\
\x VAR a,b,c,d : Complex...
..., 6.6); \\
\x d := Complex.Add(a,Complex.Add(b,c)); \\
END Use.
\end{gprogram}

MemoryLeaks-Complex

6 Fragmentation


\begin{gprogram}
\x VAR a, b, c, d : POINTER TO \\
\xxx ARRAY [1..1000] OF BYTE...
...; NEW(b); NEW(c); NEW(d); \\
\x DISPOSE(a); DISPOSE(c); NEW(x);
\end{gprogram}
Fragmentation

7 Implicit Deallocation

8 Implicit Deallocation...

9 Algorithm: Reference Counts

10 Algorithm: Reference Counts...

ReferenceCounts

11 Algorithm: Reference Counts...

NEW(p) is implemented as:
\begin{gprogram}
\xx malloc(p); p$\uparrow$.rc := 0;
\end{gprogram}

p$\uparrow$.next:=q is implemented as:
\begin{gprogram}
\xx z := p$\uparrow$.next; \\
\xx if z $\neq$\ nil then \\
\x...
...x endif; \\
\xx p$\uparrow$.next := q; \\
\xx q$\uparrow$.rc++;
\end{gprogram}

12 Readings and References

13 Readings and References...



Christian Collberg 2008-01-30