Lecture 12: Arrays, Pointers, Recursive Types, & Garbage Collection
Lecture 12: Arrays, Pointers, Recursive Types, & Garbage Collection
Garbage Collection
COMP 524 Programming Language Concepts
Aaron Block
February 27, 2007
row-major
order
Column-
major order
S U N S U N M
M O N O N T U
T U E E W E D
W E D T H U
T H U F R I S
F R I A T
S A T
The University of North Carolina at Chapel Hill 5
Arrays: Address Calculations
A: array [L1..U1] of array [L2..U2] of array [l3..U3]
of element_type
L3
j L1
L2
k
L3
j L1
S3 = size of element
S2 = (U3-L3+1) x S3 L2
k S1 = (U2 - L2 +1) x S2
Address of A[i,j,k]
Address
i of A + (i-L1)xS1 + (j-L2)xS2 + (k-L3)xS3
L3
j L1
Optimized
(i x S1) + (j x S2) + (k x S3) + address A - L2
[(L1
k x S1) + (L2 x S2) + (L3 x S3)].
the phrase [(L1 x S1) + (L2 x S2) + (L3 x S3)] can be
i determined at compile-time
•Pointers
• Used in value model of variables
• Not necessary for reference model
•Dangling References
•Garbage Collection
struct chr_tree{
struct chr_tree *l, *r; C
char var;
}
type chr_tree;
Ada
type chr_tree_ptr is access chr_tree;
type chr_tree is record
left,right:chr_tree_ptr;
val:characte;
end record;
R C
X Y
Z W
C C C Lisp
A R
C C C C C C
A X A Y
C C C
A Z
C C C
A W
‘(#\R (#\X () ()) (#\Y (#\Z () ()) (#\W () ())))
ptr1 ptr2
ptr2
new(ptr1); ptr1
ptr1
ptr2 := ptr1;
ptr2
ptr1
delete(ptr1);
ptr2
ptr1:135942
135942
ptr2 := ptr1;
ptr2:135942
ptr1:135942 0
delete(ptr1);
ptr2:135942
• Algorithm:
• Mark every block in the heap as useless
• Starting with all pointers outside the heap, recursively explore
all linked data structures
• Add every block that remain marked to the free list.
• Run whenever free space is low
X Y
Z W
X Y
Z W
X Y
Z W
X Y
Z W
X Y
Z W
X Y
Z W