Docsity

Allocation, Deal location and Reference Counting - Study Guide | CS 5510, Study notes of Programming Languages

Partial preview of the text

Download Allocation, Deal location and Reference Counting - Study Guide | CS 5510 and more Study notes Programming Languages in PDF only on Docsity!

Allocation

Constructor calls are allocation:

; interp

:^ -> void (define

(interp)(type-case^ CFAE^ fae-reg ...[cfun (body-expr) (begin(set!

v-reg (closureV

body-expr

ds-reg))

(continue))] ...)); continue

: ->^

void (define

(continue

k v) ...[addSecondK (r ds

k)(begin(set!^ fae-reg

r) (set!^ sc-reg ds) (set!^ k-reg^ (doAddK

v-reg k))

(interp))] ...)

Deallocation

Where does

free^

go?

; continue

:^ -> void (define

(continue)...[doAddK (v1 k)(begin(set!

v-reg (num+ v1^ v-reg)) (free k-reg)

(set!^ k-reg^ k) (continue))] ...[doAppK (fun-val

k) (begin(set!

fae-reg

(closureV-body

fun-val))

(set!^ ds-reg (cons v-reg(closureV-ds

fun-val)))

(set!^ k-reg^ k) (free fun-val)

(interp))] ...)

Deallocation

[doAppK (fun-val

k) (begin(set!

fae-reg

(closureV-body

fun-val))

(set!^ ds-reg (cons v-reg(closureV-ds

fun-val)))

(set!^ k-reg^ k) (free fun-val)

(interp))]

• This free is

not^ ok, because the closure might be kept in a

substitution somewhere• Need to free only if no one else is using it...

Reference Counting

Reference counting:

a way to know whether a record has other

users• Attatch a count to every record, starting at 0• When installing a pointer to a record (into a register or anotherrecord), increment its count• When replacing a pointer to a record, decrement its count• When a count is decremented to 0, decrement counts for otherrecords referenced by the record, then free it

5-

Reference Counting 1

Adjust counts when a pointeris changed...

Reference Counting 1

... freeing a record if its countgoes to 0

Reference Counting 1

Adjust counts after frees, too...

Reference Counting 1

... which can trigger more frees

Reference Counting And Cycles^11

An assignment can create acycle...

Reference Counting And Cycles^11

Adding a reference incrementsa count

Garbage Collection

Garbage collection:

a way to know whether a record is

accessible

• A record referenced by a register is

live

• A record referenced by a live record is also live• A program can only possibly use live records, because there is noway to get to other records• A garbage collector frees all records that are not live• Allocate until we run out of memory, then run a garbage collector toget more space

17-

Garbage Collection Algorithm

• Color all records

white

• Color records referenced by registers

gray

• Repeat until there are no gray records:Pick a gray record,

r

For each white record that

r^ points to, make it gray

Color^ r

black

• Deallocate all white records

Garbage Collection

Mark records referenced byregisters as gray

Garbage Collection

Need to pick a gray recordRed arrow indicates thechosen record