Programming Language Implementation

Size: px
Start display at page:

Download "Programming Language Implementation"

Transcription

1 A Practical Introduction to Programming Language Implementation 2014: Week 10 Garbage Collection College of Information Science and Engineering Ritsumeikan University 1

2 review of last week s topics dynamic and static (lexical) scoping functions actual arguments formal parameters body lexical scoping free variables higher-order functions functions as closures user-defined functions project: add user-defined functions (closures) to your language 2

3 this week s topics memory management the need for garbage collection precise collectors tracing, reference counting copying, compacting and fragmenting generation scavenging non-precise (conservative) collectors program memory image segments: text, data, stack implementation complications due to GC tagged immediate values to reduce GC overhead project: add garbage collection to your language 3

4 memory management the execution of a program generates data structures dynamically the program uses malloc() to allocate some memory which is filled with data according to some program type we call these structs/arrays/etc. by the generic term memory object or usually just object objects can contain pointers to other objects thereby forming a tree or graph of objects memory management is the process of reclaiming their storage by calling free() when an object is no longer needed therefore, in a correct program: every malloc() must eventually have a corresponding free() 4

5 garbage collection without memory management, memory would become exhausted your program will be terminated by the OS, or... malloc() returns NULL instead of memory which, of course, you forget to check for and your program crashes manual memory management relies on program(mer) logic this is tedious and error-prone failing to free() an object leads to memory leaks prematurely free()ing an object leads to dangling pointers free()ing the same an object twice leads to run-time errors (sometimes called double-free bugs ) garbage collection is the process of automatically calling free() when, and only when, it is safe to do so (GC was invented by John McCarthy in 1959 for his Lisp language) 5

6 detecting garbage a variable that stores a pointer to an object is called a root objects can contain pointers to other objects we have a graph of pointers to objects we can ignore cycles, so the graph becomes a tree the top of a tree is called its root objects that are reachable from a root are considered live by following (transitively) one or more pointers all other objects are unreachable and therefore garbage they can never again be used in the computation and must be collected so their memory can be reclaimed to prevent memory exhaustion 6

7 roots, live objects and garbage roots memory objects foo bar live baz global variables, local vaiables, function arguments, etc. garbage 7

8 precise collectors two kinds of garbage collection precisely identify all objects that are garbage most efficient use of memory can be intrusive require cooperation from the programmer and/or the language implementation two approaches: tracing and reference counting non-precise (conservative) collectors conservatively estimate which objects are garbage less efficient use of memory least intrusive often a drop-in replacement for malloc() only one approach: scan the whole of memory for potential roots 8

9 precise collection: tracing determine which objects should be collected by removing live objects from the set of all objects what remains are the dead objects recursively follow object references, starting from the root objects until all live objects have been visited any objects not visited are unreachable (or inaccessible) they can be collected and their storage reclaimed many algorithms and implementations from very simple to very complex one of the simplest is mark-and-sweep effective for small numbers of objects (thousands rather than millions) relatively low rates of allocation 9

10 precise collection: mark and sweep root objects object memory before collection M starting from a root, mark accessible object mark phase M M M following pointers in that object, mark transitively-accessible objects repeat until... M M M M all live objects are marked; remaining objects are unreachable garbage sweep phase storage for dead objects can be reclaimed and reused 10

11 precise collection: mark and sweep 1. initialisation: for each object p set is_marked(p) = false 2. mark phase: calculate the transitive closure of reachable objects for each root r call mark_and_trace(r) where mark_and_trace(p) = if is_marked(p) then return set is_marked(p) = true for each pointer q in p call mark_and_trace(q) any objects still not marked are unreachable (or inaccessible) 3. sweep phase: for each object p if is_not_marked(p) then free(p) 11

12 advantages: precise collection: mark and sweep simple (a few tens of lines of C) does not require any special data structures can be a wrapper around malloc() fast, for small object populations disadvantages: does not scale: cost is linear in the size of the object memory requires additional information ( is-marked bit) within objects must be able to enumerate (iterate over) all objects requires precise knowledge of object layout (location of pointers) requires precise knowledge of roots explicit declaration of global root variables explicit protection of local roots function arguments, local variables, intermediate results 12

13 tracing collectors: programming complications all roots must be identified to the collector global variables containing roots function arguments containing temporary references local variables containing temporary references tedious and very error-prone object *foo(object *arg) { GC_protect(arg); /* temporary root */ object *bar = twiddle(arg); GC_protect(bar); /* temporary root */ run_fermat_solver(); /* potential GC here */ GC_unprotect(bar); GC_unprotect(arg); return bar; } bugs can take months to find and days to diagnose 13

14 fragmentation consider the situation at the end of our mark-sweep collection total available memory for allocation recently-reclaimed objects four units of memory are unused, but the largest object we can allocate is two units after which we can only allocate two more objects of one unit the four units of available memory are fragmented 14

15 memory compaction a compacting collector removes fragmentation sweep phase groups live objects together available space is left in one contiguous region live objects compacted to start of memory available memory is contiguous more complex than simple mark-sweep recently-reclaimed objects all pointers must be updated with new locations of objects 15

16 precise collection: reference counting the opposite of tracing while the application is executing... record the total number of references that exist to each object when the count reaches zero, the object is unreachable incoming references reference_count = 3 application fields... 16

17 precise collection: reference counting reference counting relies on a write barrier when an existing pointer is overwritten decrement the reference count of the object it refers to if the count has reached zero, collect the object when a pointer is stored in a variable or other memory location increment the reference count of the object it refers to obj reference_count = 1 pointer_member = &p... p reference_count = 1 q reference_count = 1 obj.pointer_member := q obj p garbage reference_count = 1 pointer_member = &q... reference_count = 0 q reference_count = 2 17

18 precise collection: reference counting a typical write barrier might be implemented like this: object *store_pointer(object **location, object *pointer) { if (*location) { (*location)->reference_count -= 1; if ((*location)->reference_count == 0) { /* decrement the ref counts of all pointer */ /* fields in the object at *location and */ /* then reclaim its storage */ collect(*location); } } *location = pointer; if (pointer) pointer->reference_count += 1; return pointer; } all stores to pointer variables must use this function programmer discipline has to enforce this special naming and macros for setters can help 18

19 advantages precise collection: reference counting objects are collected as soon as they become unreachable reference counting has good locality with computation reference_count word tends to be in the CPU cache disadvantages decrementing one reference count can lead to mass extinction avalanche of reference counts reaching zero potential pause in program execution can be mitigated by (e.g.) incremental sweeping round-robin check for zero ref counts during allocation one object checked/deallocated per object allocated cycles must be broken explicitly programmer must predict cycles, store NULL to break them or have a secondary tracing collector to periodically find them 19

20 precise collection: reference counting a cycle of unreachable garbage with non-zero reference count ref_count = 1 ref_count = 1 ref_count = 1 ref_count = 1 20

21 precise collection: reference counting an avalanche of collections waiting to happen pointer about to be overwritten ref_count = 1 ref_count = 1... one million objects with ref_count = 1... ref_count = 1 21

22 non-precise (conservative) collectors all data values in a program can be enumerated those that appear to be pointers to memory blocks can be identified if a word looks like a pointer, it is assumed to be a pointer some will not be pointers: integers, floats, strings, etc. some objects that are not live will be considered live hence non-precise and conservative collector any objects with no such pointers are unreachable the program can never refer to them again they can be collected and recycled 22

23 non-precise collection: program memory image text segment contains the program data and stack segments contain variables variables can contain roots heap contains objects program start of memory machine code instructions initialized variables uninitialized variables text segment data segment scanning the data and stack segments provides potential root pointers to heap objects data heap malloc()- allocated objects pointers to addresses outside of heap can be ignored run-time stack end of memory stack segment 23

24 non-precise collection conservative collector advantages: almost transparent to the programmer replace malloc with GC_malloc, remove calls to free no need to declare root variables, etc. conservative collector disadvantages: false pointers look like roots, preventing reclamation unpredictable run-time memory requirements (almost always more than is really in use) actual value pointer value (void *) malloc(32) (void *) 0x (int) (void *) 0x000f4240 (char []) "ptr" (void *) 0x (float) 0.0 (void *) 0x3f (void *) &printf (void *) 0x

25 generation scavenging objects tend to do one of two things: die very quickly (e.g., arithmetic intermediate results) last a long time (e.g., data structures, global environments, etc.) generational collectors exploit this by having two memory areas new space is where objects are born new space is small, and traced/collected frequently objects that outlive several new space collections are tenured they are moved to old space old space is large, and traced/collected rarely new space therefore contains only young objects most of which will die during collections and therefore cost very little to trace, mark and compact 25

26 generation scavenging new space old space new objects garbage collection & compaction allocation collection & compaction survivors tenured to old space 26

27 tagged immediate values to reduce GC overhead alignment rules mean pointers to objects are always even actually, multiples of 4 or even 8 we can use an odd pointer to encode 31 bits of information LS bit is set to 0 for pointers, 1 for non-pointers pointer to object in memory 31 bits of non-pointer value

28 tagged immediate values to reduce GC overhead in our language, integer arithmetic allocates objects Token *primitive_add(token *operands) { return make_integer(operands->first.integer + operands->second.integer); } if 31-bit integers are sufficient, we can encode them within a pointer void *make_integer(int i) { return (void *)((i << 1) 1); } int get_integer(void *p) { return (int)p >> 1; } Token *primitive_add(token *operands) { return make_integer(get_integer(operands->first) + get_integer(operands->second)); } these are called tagged integers 28

29 garbage collection summary application allocates objects until some threshold is crossed; e.g: number of objects allocated total size of objects allocated GC identifies live objects and garbage (dead objects) object graph tracing conservative scan for pointers GC collects dead objects, reclaims their unused storage possibly only on objects younger than a certain generation GC tidies up memory to reduce fragmentation compaction (copy or move objects to make them contiguous) application continues reference counting is an alternative approach with different trade-offs 29

30 project: add garbage collection to your language check memory usage for your interpreter running this program (define x 0) (while 1 (print (assign x (add x 1)))) Boehm-Demers-Weiser Garbage Collector popular conservative collector for C and C++ home page: Linux (Debian/Ubuntu): apt-get install libgc-dev MacOS X (via Homebrew): brew install boehmgc Windows (Cygwin): install libgc-devel from setup.exe 30

31 project: add garbage collection to your language drop-in replacement for malloc() install libgc add #include <gc/gc.h> to your program replace calloc() with GC_malloc() in make_token() call GC_INIT(): at the start of main() link your interpreter with -lgc Token *make_token(int type) { Token *token = GC_malloc(sizeof(Token)); /*... */ } int main(int argc, char **argv) { GC_INIT(); /*... */ } the program should now run without consuming all available memory 31

32 glossary allocate obtain memory from the operating system and give it to the program for use in storing data. available space the amount of memory that is available for allocation. collect (an object) perform any final actions on the object (such as collecting any objects it references) and then reclaim the storage allocated to it. compact move live objects together, eliminating spaces between them, to reduce memory fragmentation. conservative cautious. In garbage collection, a non-precise collector that makes a cautious estimation of which objects are unreachable. If there is any doubt at all, an object will be considered reachable. This results in safe collection, but less than optimal use of memory. 32

33 contiguous having no gaps. cycle a series of pointer references which eventually lead back to the same object or location. In a reference-counting GC, a cycle can artificially maintain a non-zero reference count in all of its objects even though those objects are unreachable and therefore garbage. dangling pointer a pointer that can be used by the program in future computation but whose referent object has been collected prematurely. When the pointer is dereferenced unexpected things will happen, including but not limited to the program crashing. data segment the area of a program s memory space in which the variables and malloc()-allocated memory resides. Grows as needed towards higher addresses. deallocate return memory that is being used to store data from the program to the operating system. decrement reduce by one. 33

34 double-free call free() on a pointer twice. The results are unpredictable, including but not limited to the program crashing. exhaustion (memory or other resource) running out, leaving none available for use by the program. fragmentation breaking up of some quantity (such as available memory) into smaller pieces, making it impossible to use all the available resource or any amount of it larger than the largest of those pieces. garbage unreachable objects that can never be used by a program for future computation. garbage collection deallocation of objects that have become unreachable. 34

35 generational collector a collector that uses two or more distinct spaces, in which objects of different ages are stored and garbage collected. Generational collectors exploit the observation that objects tend to either last a very short time or a very long time. graph a structure containing objects (nodes) and references (edges) from objects to other objects. inaccessible something that can no longer be accessed. Synonymous with unreachable. incremental doing a little work at a time, rather than all the work at once. An incremental collector typically performs a little collection work every time an object is allocated. This prevents long pauses due to the collection of many objects at the same time. increment increase by one. live not dead; still reachable by the program. 35

36 mark phase the phase of a mark-sweep collector in which the object graph is traced and all reachable objects are marked as live. mark-and-sweep a collector in which a mark phase identifies live objects and then a sweep phase deallocates dead objects, possibly compacting the live objects in the process to eliminate fragmentation. memory leak failure to deallocate a garbage object and reclaim its storage, preventing that storage from being used again by the program. memory management ensuring the efficient use of memory. For example, ensuring that all memory objects are deallocated when they are no longer needed by the program. new space the region in a generational collector into which new objects are born. If they have not been collected after several generations (garbage collections) have elapsed, they will be tenured into old space. New space is traced and collected much more frequently than old space. 36

37 non-precise a garbage collector that makes a conservative estimate of which objects are live, rather than attempting to make a precise determination based on tracing. object a region of memory that was allocated to the program by malloc(). old space a region in a generational collector into which objects that have survived for several generations (garbage collections) are tenured. Old space is traced and collected far less frequently than new space. precise a collector that traces the object graph to determine exactly which objects are live and which objects are garbage. reachable something that can the program can access by following a chain of one or more pointers. reclaim return memory to the system, e.g., by calling free(). 37

38 reference counting identifying garbage by keeping a count of the total number of references that exist to each object. When the count drops to zero, the object is garbage. root a variable or other memory location that contains a pointer to an object and which the program can be access by name, or by some other mechanism that does not involve following another reference. Objects referenced from roots can therefore be used in future computation and are always considered live. round-robin performing a sequence of tasks, or processing pieces of data, one after the other and wrapping around from the last back to the first. stack segment the region of memory in which the program s call stack is located. Usually grows towards lower memory addresses. 38

39 sweep phase a phase in a mark-sweep collector during which dead objects are deallocated and their storage reclaimed. Live objects can also be compacted during this phase to eliminate fragmentation. tagged integer an integer whose value is encoded in an object pointer. Tagged integers are distinguished from pointers by having some property that is impossible for a pointer, such as the least significant bit being set (an odd address) in a system where the minimum alignment of memory objects is 4 or 8. tenure to move an object from new space to old space when it has survived a certain number of generations and is therefore likely to survive for many more. text segment the region of a program s memory in which the machine code instructions (the text of the program, written in machine language) is stored. This region is usually of a fixed size and often located at the start of memory. 39

40 trace to follow a graph of object references, starting from one or more roots, in order to calculate the transitive closure of reachable objects in a program s memory. transitive a mathematical relation having the property that whenever A is related to B and B is related to C, then A is also related to C. In computer memory, object reachability (by following pointers) is a transitive relationship. transitive closure the set of all items that can be related, by a transitive relation, to some initial item. In computer memory, the transitive closure of reachable objects starting from the roots is the set of all reachable objects. tree a graph in which cycles have been removed. unreachable an object that is inaccessible to the program. No reference to the object exists either in the program s variables or in any other object that is reachable by the program. 40

41 write barrier a piece of code that is executed before and/or after performing a write operation on a location of importance. In garbage collection, a write barrier can be used to detect a significant mutation of a pointer variable for purposes such as reference counting. 41

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime Runtime The optimized program is ready to run What sorts of facilities are available at runtime Compiler Passes Analysis of input program (front-end) character stream Lexical Analysis token stream Syntactic

More information

Lecture 13: Garbage Collection

Lecture 13: Garbage Collection Lecture 13: Garbage Collection COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer/Mikkel Kringelbach 1 Garbage Collection Every modern programming language allows programmers

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 Spring 2017 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC330 Fall 2018 1 Memory Attributes Memory to store data in programming languages has the following lifecycle

More information

Implementation Garbage Collection

Implementation Garbage Collection CITS 3242 Programming Paradigms Part IV: Advanced Topics Topic 19: Implementation Garbage Collection Most languages in the functional, logic, and object-oriented paradigms include some form of automatic

More information

Lecture 15 Garbage Collection

Lecture 15 Garbage Collection Lecture 15 Garbage Collection I. Introduction to GC -- Reference Counting -- Basic Trace-Based GC II. Copying Collectors III. Break Up GC in Time (Incremental) IV. Break Up GC in Space (Partial) Readings:

More information

Garbage Collection Algorithms. Ganesh Bikshandi

Garbage Collection Algorithms. Ganesh Bikshandi Garbage Collection Algorithms Ganesh Bikshandi Announcement MP4 posted Term paper posted Introduction Garbage : discarded or useless material Collection : the act or process of collecting Garbage collection

More information

Run-time Environments -Part 3

Run-time Environments -Part 3 Run-time Environments -Part 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Compiler Design Outline of the Lecture Part 3 What is run-time support?

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Run-Time Environments/Garbage Collection

Run-Time Environments/Garbage Collection Run-Time Environments/Garbage Collection Department of Computer Science, Faculty of ICT January 5, 2014 Introduction Compilers need to be aware of the run-time environment in which their compiled programs

More information

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35 Garbage Collection Akim Demaille, Etienne Renault, Roland Levillain May 15, 2017 CCMP2 Garbage Collection May 15, 2017 1 / 35 Table of contents 1 Motivations and Definitions 2 Reference Counting Garbage

More information

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides Garbage Collection Last time Compiling Object-Oriented Languages Today Motivation behind garbage collection Garbage collection basics Garbage collection performance Specific example of using GC in C++

More information

Dynamic Memory Management! Goals of this Lecture!

Dynamic Memory Management! Goals of this Lecture! Dynamic Memory Management!!! 1 Goals of this Lecture! Help you learn about:! Dynamic memory management techniques! Garbage collection by the run-time system (Java)! Manual deallocation by the programmer

More information

Dynamic Memory Management

Dynamic Memory Management Dynamic Memory Management 1 Goals of this Lecture Help you learn about: Dynamic memory management techniques Garbage collection by the run-time system (Java) Manual deallocation by the programmer (C, C++)

More information

Exploiting the Behavior of Generational Garbage Collector

Exploiting the Behavior of Generational Garbage Collector Exploiting the Behavior of Generational Garbage Collector I. Introduction Zhe Xu, Jia Zhao Garbage collection is a form of automatic memory management. The garbage collector, attempts to reclaim garbage,

More information

Run-time Environments - 3

Run-time Environments - 3 Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time

More information

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection Deallocation Mechanisms User-controlled Deallocation Allocating heap space is fairly easy. But how do we deallocate heap memory no longer in use? Sometimes we may never need to deallocate! If heaps objects

More information

Robust Memory Management Schemes

Robust Memory Management Schemes Robust Memory Management Schemes Prepared by : Fadi Sbahi & Ali Bsoul Supervised By: Dr. Lo ai Tawalbeh Jordan University of Science and Technology Robust Memory Management Schemes Introduction. Memory

More information

Garbage Collection (1)

Garbage Collection (1) Garbage Collection (1) Advanced Operating Systems Lecture 7 This work is licensed under the Creative Commons Attribution-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nd/4.0/

More information

Algorithms for Dynamic Memory Management (236780) Lecture 4. Lecturer: Erez Petrank

Algorithms for Dynamic Memory Management (236780) Lecture 4. Lecturer: Erez Petrank Algorithms for Dynamic Memory Management (236780) Lecture 4 Lecturer: Erez Petrank!1 March 24, 2014 Topics last week The Copying Garbage Collector algorithm: Basics Cheney s collector Additional issues:

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Compiler Construction D7011E

Compiler Construction D7011E Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 First: Run-time Systems 2 The Final Component:

More information

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1 CS 345 Garbage Collection Vitaly Shmatikov slide 1 Major Areas of Memory Static area Fixed size, fixed content, allocated at compile time Run-time stack Variable size, variable content (activation records)

More information

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008 Dynamic Storage Allocation CS 44: Operating Systems Spring 2 Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need to grow or shrink. Dynamic

More information

Automatic Garbage Collection

Automatic Garbage Collection Automatic Garbage Collection Announcements: PS6 due Monday 12/6 at 11:59PM Final exam on Thursday 12/16 o PS6 tournament and review session that week Garbage In OCaml programs (and in most other programming

More information

Heap Management. Heap Allocation

Heap Management. Heap Allocation Heap Management Heap Allocation A very flexible storage allocation mechanism is heap allocation. Any number of data objects can be allocated and freed in a memory pool, called a heap. Heap allocation is

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

Dynamic Memory Management

Dynamic Memory Management Dynamic Memory Management Professor Jennifer Rexford http://www.cs.princeton.edu/~jrex 1 Goals of Today s Lecture Dynamic memory management o Garbage collection by the run-time system (Java) o Manual deallocation

More information

Automatic Memory Management

Automatic Memory Management Automatic Memory Management Why Automatic Memory Management? Storage management is still a hard problem in modern programming Why Automatic Memory Management? Storage management is still a hard problem

More information

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture: CS 537 Introduction to Operating Systems UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is

More information

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley Managed runtimes & garbage collection CSE 6341 Some slides by Kathryn McKinley 1 Managed runtimes Advantages? Disadvantages? 2 Managed runtimes Advantages? Reliability Security Portability Performance?

More information

Managed runtimes & garbage collection

Managed runtimes & garbage collection Managed runtimes Advantages? Managed runtimes & garbage collection CSE 631 Some slides by Kathryn McKinley Disadvantages? 1 2 Managed runtimes Portability (& performance) Advantages? Reliability Security

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) COMP 412 FALL 2017 Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java) Copyright 2017, Keith D. Cooper & Zoran Budimlić, all rights reserved. Students enrolled in Comp 412 at Rice

More information

CS Computer Systems. Lecture 8: Free Memory Management

CS Computer Systems. Lecture 8: Free Memory Management CS 5600 Computer Systems Lecture 8: Free Memory Management Recap of Last Week Last week focused on virtual memory Gives each process the illusion of vast, empty memory Offers protection and isolation 31

More information

Garbage Collection. Steven R. Bagley

Garbage Collection. Steven R. Bagley Garbage Collection Steven R. Bagley Reference Counting Counts number of pointers to an Object deleted when the count hits zero Eager deleted as soon as it is finished with Problem: Circular references

More information

Garbage Collection. Hwansoo Han

Garbage Collection. Hwansoo Han Garbage Collection Hwansoo Han Heap Memory Garbage collection Automatically reclaim the space that the running program can never access again Performed by the runtime system Two parts of a garbage collector

More information

Opera&ng Systems CMPSCI 377 Garbage Collec&on. Emery Berger and Mark Corner University of Massachuse9s Amherst

Opera&ng Systems CMPSCI 377 Garbage Collec&on. Emery Berger and Mark Corner University of Massachuse9s Amherst Opera&ng Systems CMPSCI 377 Garbage Collec&on Emery Berger and Mark Corner University of Massachuse9s Amherst Ques

More information

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection CS577 Modern Language Processors Spring 2018 Lecture Garbage Collection 1 BASIC GARBAGE COLLECTION Garbage Collection (GC) is the automatic reclamation of heap records that will never again be accessed

More information

Compiler Construction

Compiler Construction Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-16/cc/ Recap: Static Data Structures Outline of Lecture 18 Recap:

More information

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing

More information

Limitations of the stack

Limitations of the stack The heap hic 1 Limitations of the stack int *table_of(int num, int len) { int table[len+1]; for (int i=0; i

More information

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11 CS 536 Spring 2015 1 Handling Overloaded Declarations Two approaches are popular: 1. Create a single symbol table

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting

More information

CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers

CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers CS 4120 Lecture 37 Memory Management 28 November 2011 Lecturer: Andrew Myers Heap allocation is a necessity for modern programming tasks, and so is automatic reclamation of heapallocated memory. However,

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 18: Code Generation V (Implementation of Dynamic Data Structures) Thomas Noll Lehrstuhl für Informatik 2 (Software Modeling and Verification) noll@cs.rwth-aachen.de http://moves.rwth-aachen.de/teaching/ss-14/cc14/

More information

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1 Compilers 8. Run-time Support Laszlo Böszörmenyi Compilers Run-time - 1 Run-Time Environment A compiler needs an abstract model of the runtime environment of the compiled code It must generate code for

More information

Name, Scope, and Binding. Outline [1]

Name, Scope, and Binding. Outline [1] Name, Scope, and Binding In Text: Chapter 3 Outline [1] Variable Binding Storage bindings and lifetime Type bindings Type Checking Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur 2

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

Memory Management. Memory Management... Memory Management... Interface to Dynamic allocation

Memory Management. Memory Management... Memory Management... Interface to Dynamic allocation CSc 453 Compilers and Systems Software 24 : Garbage Collection Introduction Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2009 Christian Collberg Dynamic Memory Management

More information

Lecture Notes on Garbage Collection

Lecture Notes on Garbage Collection Lecture Notes on Garbage Collection 15-411: Compiler Design André Platzer Lecture 20 1 Introduction In the previous lectures we have considered a programming language C0 with pointers and memory and array

More information

A.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2

A.Arpaci-Dusseau. Mapping from logical address space to physical address space. CS 537:Operating Systems lecture12.fm.2 UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department CS 537 A. Arpaci-Dusseau Intro to Operating Systems Spring 2000 Dynamic Memory Allocation Questions answered in these notes When is a stack

More information

Advanced Programming & C++ Language

Advanced Programming & C++ Language Advanced Programming & C++ Language ~6~ Introduction to Memory Management Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan Stack & Heap 2 The memory a program uses is typically divided into four different

More information

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return Last week Data can be allocated on the stack or on the heap (aka dynamic memory) Data on the stack is allocated automatically when we do a function call, and removed when we return f() {... int table[len];...

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Dynamic Storage Allocation

Dynamic Storage Allocation 6.172 Performance Engineering of Software Systems LECTURE 10 Dynamic Storage Allocation Charles E. Leiserson October 12, 2010 2010 Charles E. Leiserson 1 Stack Allocation Array and pointer A un Allocate

More information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

One-Slide Summary. Lecture Outine. Automatic Memory Management #1. Why Automatic Memory Management? Garbage Collection.

One-Slide Summary. Lecture Outine. Automatic Memory Management #1. Why Automatic Memory Management? Garbage Collection. Automatic Memory Management #1 One-Slide Summary An automatic memory management system deallocates objects when they are no longer used and reclaims their storage space. We must be conservative and only

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates

More information

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2 CPSC 213 Introduction to Computer Systems Winter Session 2017, Term 2 Unit 1c Jan 24, 26, 29, 31, and Feb 2 Instance Variables and Dynamic Allocation Overview Reading Companion: Reference 2.4.4-5 Textbook:

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

6.172 Performance Engineering of Software Systems Spring Lecture 9. P after. Figure 1: A diagram of the stack (Image by MIT OpenCourseWare.

6.172 Performance Engineering of Software Systems Spring Lecture 9. P after. Figure 1: A diagram of the stack (Image by MIT OpenCourseWare. 6.172 Performance Engineering of Software Systems Spring 2009 Lecture 9 MIT OpenCourseWare Dynamic Storage Allocation Stack allocation: LIFO (last-in-first-out) Array and pointer A used unused P before

More information

Garbage Collection. Vyacheslav Egorov

Garbage Collection. Vyacheslav Egorov Garbage Collection Vyacheslav Egorov 28.02.2012 class Heap { public: void* Allocate(size_t sz); }; class Heap { public: void* Allocate(size_t sz); void Deallocate(void* ptr); }; class Heap { public: void*

More information

Garbage Collection Techniques

Garbage Collection Techniques Garbage Collection Techniques Michael Jantz COSC 340: Software Engineering 1 Memory Management Memory Management Recognizing when allocated objects are no longer needed Deallocating (freeing) the memory

More information

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

Memory Management. Didactic Module 14 Programming Languages - EEL670 1 Memory Management Didactic Module 14 Programming Languages - EEL670 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc, etc.

More information

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Memory Management Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc,

More information

Hard Real-Time Garbage Collection in Java Virtual Machines

Hard Real-Time Garbage Collection in Java Virtual Machines Hard Real-Time Garbage Collection in Java Virtual Machines... towards unrestricted real-time programming in Java Fridtjof Siebert, IPD, University of Karlsruhe 1 Jamaica Systems Structure Exisiting GC

More information

Dynamic Memory Allocation: Advanced Concepts

Dynamic Memory Allocation: Advanced Concepts Dynamic Memory Allocation: Advanced Concepts Keeping Track of Free Blocks Method 1: Implicit list using length links all blocks 5 4 6 Method : Explicit list among the free blocks using pointers 5 4 6 Kai

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Memory Management: The Details

Memory Management: The Details Lecture 10 Memory Management: The Details Sizing Up Memory Primitive Data Types Complex Data Types byte: char: short: basic value (8 bits) 1 byte 2 bytes Pointer: platform dependent 4 bytes on 32 bit machine

More information

Run-time Environments

Run-time Environments Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction

More information

Run-time Environments

Run-time Environments Run-time Environments Status We have so far covered the front-end phases Lexical analysis Parsing Semantic analysis Next come the back-end phases Code generation Optimization Register allocation Instruction

More information

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda Manual llocation Dynamic memory allocation is an obvious necessity in a programming environment. S 1622: Garbage ollection Many programming languages expose some functions or keywords to manage runtime

More information

Shenandoah An ultra-low pause time Garbage Collector for OpenJDK. Christine H. Flood Roman Kennke

Shenandoah An ultra-low pause time Garbage Collector for OpenJDK. Christine H. Flood Roman Kennke Shenandoah An ultra-low pause time Garbage Collector for OpenJDK Christine H. Flood Roman Kennke 1 What does ultra-low pause time mean? It means that the pause time is proportional to the size of the root

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

Performance of Non-Moving Garbage Collectors. Hans-J. Boehm HP Labs

Performance of Non-Moving Garbage Collectors. Hans-J. Boehm HP Labs Performance of Non-Moving Garbage Collectors Hans-J. Boehm HP Labs Why Use (Tracing) Garbage Collection to Reclaim Program Memory? Increasingly common Java, C#, Scheme, Python, ML,... gcc, w3m, emacs,

More information

Lecture 13: Complex Types and Garbage Collection

Lecture 13: Complex Types and Garbage Collection Lecture 13: Complex Types and Garbage Collection COMP 524 Programming Language Concepts Stephen Olivier March 17, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts

More information

A new Mono GC. Paolo Molaro October 25, 2006

A new Mono GC. Paolo Molaro October 25, 2006 A new Mono GC Paolo Molaro lupus@novell.com October 25, 2006 Current GC: why Boehm Ported to the major architectures and systems Featurefull Very easy to integrate Handles managed pointers in unmanaged

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Garbage Collection (2) Advanced Operating Systems Lecture 9

Garbage Collection (2) Advanced Operating Systems Lecture 9 Garbage Collection (2) Advanced Operating Systems Lecture 9 Lecture Outline Garbage collection Generational algorithms Incremental algorithms Real-time garbage collection Practical factors 2 Object Lifetimes

More information

Garbage Collection. CS 351: Systems Programming Michael Saelee

Garbage Collection. CS 351: Systems Programming Michael Saelee Garbage Collection CS 351: Systems Programming Michael Saelee = automatic deallocation i.e., malloc, but no free! system must track status of allocated blocks free (and potentially reuse)

More information

Lecture 15 Advanced Garbage Collection

Lecture 15 Advanced Garbage Collection Lecture 15 Advanced Garbage Collection I. Break Up GC in Time (Incremental) II. Break Up GC in Space (Partial) Readings: Ch. 7.6.4-7.7.4 CS243: Advanced Garbage Collection 1 Trace-Based GC: Memory Life-Cycle

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace Project there are a couple of 3 person teams regroup or see me or forever hold your peace a new drop with new type checking is coming using it is optional 1 Compiler Architecture source code Now we jump

More information

Lecture Notes on Memory Management

Lecture Notes on Memory Management Lecture Notes on Memory Management 15-122: Principles of Imperative Computation Frank Pfenning Lecture 21 April 5, 2011 1 Introduction Unlike C0 and other modern languages like Java, C#, or ML, C requires

More information

Memory Allocation III

Memory Allocation III Memory Allocation III CSE 351 Spring 2017 Instructor: Ruth Anderson Teaching Assistants: Dylan Johnson Kevin Bi Linxing Preston Jiang Cody Ohlsen Yufang Sun Joshua Curtis Administrivia Homework 5 Due Wed

More information

ACM Trivia Bowl. Thursday April 3 rd (two days from now) 7pm OLS 001 Snacks and drinks provided All are welcome! I will be there.

ACM Trivia Bowl. Thursday April 3 rd (two days from now) 7pm OLS 001 Snacks and drinks provided All are welcome! I will be there. #1 ACM Trivia Bowl Thursday April 3 rd (two days from now) 7pm OLS 001 Snacks and drinks provided All are welcome! I will be there. If you are in one of the top three teams, I will give you one point of

More information

Tick: Concurrent GC in Apache Harmony

Tick: Concurrent GC in Apache Harmony Tick: Concurrent GC in Apache Harmony Xiao-Feng Li 2009-4-12 Acknowledgement: Yunan He, Simon Zhou Agenda Concurrent GC phases and transition Concurrent marking scheduling Concurrent GC algorithms Tick

More information

Garbage Collection. Weiyuan Li

Garbage Collection. Weiyuan Li Garbage Collection Weiyuan Li Why GC exactly? - Laziness - Performance - free is not free - combats memory fragmentation - More flame wars Basic concepts - Type Safety - Safe: ML, Java (not really) - Unsafe:

More information

Lecture Notes on Advanced Garbage Collection

Lecture Notes on Advanced Garbage Collection Lecture Notes on Advanced Garbage Collection 15-411: Compiler Design André Platzer Lecture 21 November 4, 2010 1 Introduction More information on garbage collection can be found in [App98, Ch 13.5-13.7]

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Review. Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young

Review. Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young Generational GC 1 Review Partitioning: Divide heap, use different strategies per heap Generational GC: Partition by age Most objects die young 2 Single-partition scanning Stack Heap Partition #1 Partition

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from

More information

CS2210: Compiler Construction. Runtime Environment

CS2210: Compiler Construction. Runtime Environment : The environment in which the program executes in at runtime Includes HW: Main memory, CPU,... Includes OS: Environment variables,... When a program is invoked The OS allocates memory for the program

More information

Run-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13

Run-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13 Run-time Environments Lecture 13 by Prof. Vijay Ganesh) Lecture 13 1 What have we covered so far? We have covered the front-end phases Lexical analysis (Lexer, regular expressions,...) Parsing (CFG, Top-down,

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

the gamedesigninitiative at cornell university Lecture 9 Memory Management

the gamedesigninitiative at cornell university Lecture 9 Memory Management Lecture 9 Gaming Memory Constraints Redux Wii-U Playstation 4 2GB of RAM 1GB dedicated to OS Shared with GPGPU 8GB of RAM Shared GPU, 8-core CPU OS footprint unknown 2 Two Main Concerns with Memory Getting

More information