Lecture 16: Automatic Memory Management
Now that our language has heap-allocated values (lambdas and tuples), the
execution of our program will rapidly produce a lot of heap allocations which
will quickly become obsolete, but we currently have no way of freeing those
objects on the heap: this will rapidly exhaust our heap space and our program
will crash. One non-solution would be to introduce a manual deletion
primitive, whereby programmers could explicitly free
some heap-allocated
value. This has several problems:
Programmers might forget to free their data, which leaves us exactly where we currently are.
Programmers might free too soon, leading to dangling pointers and (probably exploitable!) crashes.
Programmers can only reference the values inside a tuple, but they have no way of accessing the closed-over contents of a closure. If a closure closed over some heap-allocated value, and that closure were the only thing still referring to that value, then freeing the closure would inevitably leak the value. Any manual solution to this would require the programmer to maintain references to everything inside the closure, thereby “opening” it and mostly negating the benefits of closures.
But most annoyingly, programmers didn’t have to do anything explicit in order to allocate memory, so it seems unfair to force them to manually deallocate memory. Instead, we need to