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

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

! What is main memory? ! What is static and dynamic allocation? ! What is segmentation? Maria Hybinette, UGA. High Address (0x7fffffff) !

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

Run-time Environments -Part 3

Run-time Environments - 3

CS61C : Machine Structures

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

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

Memory Management. To do. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory

Dynamic Memory Management

Dynamic Storage Allocation

CMSC 330: Organization of Programming Languages

Dynamic Memory Management! Goals of this Lecture!

Operating System Labs. Yuanbin Wu

Run-Time Environments/Garbage Collection

Memory Management. q Basic memory management q Swapping q Kernel memory allocation q Next Time: Virtual memory

CS61C : Machine Structures

Operating systems. Part 1. Module 11 Main memory introduction. Tami Sorgente 1

CMSC 330: Organization of Programming Languages

Heap Management portion of the store lives indefinitely until the program explicitly deletes it C++ and Java new Such objects are stored on a heap

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

Dynamic Memory Management

CS61C : Machine Structures

CS61C : Machine Structures

CS61C Midterm Review on C & Memory Management

Memory Management (Chaper 4, Tanenbaum)

Memory Management Basics

Memory Management. COMP755 Advanced Operating Systems

Lectures 13 & 14. memory management

Review! Lecture 5 C Memory Management !

CS61C : Machine Structures

ECE 598 Advanced Operating Systems Lecture 10

Robust Memory Management Schemes

Memory Management (Chaper 4, Tanenbaum)

Lecture 13: Garbage Collection

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1

Virtualizing Memory: Paging. Announcements

Programming Language Implementation

CS399 New Beginnings. Jonathan Walpole

CS61C : Machine Structures

Advanced Programming & C++ Language

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Preview. Memory Management

Dynamic Memory Allocation

Dynamic Memory Allocation

Garbage Collection (1)

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

Memory management. Johan Montelius KTH

The Memory Management Unit. Operating Systems. Autumn CS4023

ECE 598 Advanced Operating Systems Lecture 12

CS Computer Systems. Lecture 8: Free Memory Management

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

CS61C : Machine Structures

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 13: Address Translation

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

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

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

Memory: Overview. CS439: Principles of Computer Systems February 26, 2018

Run-time Environments

Engine Support System. asyrani.com

Run-time Environments

Compiler Construction

Heap Management. Heap Allocation

Compiler Construction

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

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

CS510 Operating System Foundations. Jonathan Walpole

Fall 2017 :: CSE 306. Introduction to. Virtual Memory. Nima Honarmand (Based on slides by Prof. Andrea Arpaci-Dusseau)

In multiprogramming systems, processes share a common store. Processes need space for:

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

CS 11 C track: lecture 5

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

Memory management: outline

Memory management: outline

Administrivia. Dynamic memory allocation. More abstractly. Why is it hard? What is fragmentation really? Important decisions

Lecture 15 Garbage Collection

Memory Management. Today. Next Time. Basic memory management Swapping Kernel memory allocation. Virtual memory

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

o Code, executable, and process o Main memory vs. virtual memory

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation: Advanced Concepts

Memory Management 3/29/14 21:38

Administrivia. Project 2 due Friday at noon Midterm Monday. Midterm review section Friday Section for Project 3 next Friday

Review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with little protection

Class Information ANNOUCEMENTS

Events, Memory Management

G Programming Languages - Fall 2012

Performance of Various Levels of Storage. Movement between levels of storage hierarchy can be explicit or implicit

Requirements, Partitioning, paging, and segmentation

CS61 Section Notes. Section 5 (Fall 2011) Topics to be covered Common Memory Errors Dynamic Memory Allocation Assignment 3: Malloc

Announcements. Persistence: Log-Structured FS (LFS)

Administrivia. - Open book, open notes (but not open notebook computer) - Covers first 10 lectures of course (including today)

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Requirements, Partitioning, paging, and segmentation

Memory Allocation. General Questions

Name, Scope, and Binding. Outline [1]

OPERATING SYSTEMS. After A.S.Tanenbaum, Modern Operating Systems 3rd edition Uses content with permission from Assoc. Prof. Florin Fortis, PhD

CSC 1600 Memory Layout for Unix Processes"

Chapter 9 Memory Management

Segmentation. Multiple Segments. Lecture Notes Week 6

Transcription:

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 a heap? Andrea C. Arpaci-Dusseau Remzi H. Arpaci-Dusseau What are best-fit, first-fit, worst-fit, and buddy allocation algorithms? How can memory be freed (using reference counts or garbage collection)? Motivation for Dynamic Memory Why do processes need dynamic allocation of memory? Do not know amount of memory needed at compile time Must be pessimistic when allocate memory statically Allocate enough for worst possible case Storage is used inefficiently Recursive procedures Do not know how many times procedure will be nested Complex data structures: lists and trees struct my_t *p=(struct my_t *)malloc(sizeof(struct my_t)); Two types of dynamic allocation Stack Heap Stack Organization Definition: Memory is freed in opposite order from allocation alloc(a); alloc(b); alloc(c); free(c); alloc(d); free(d); free(b); free(a); Implementation: Pointer separates allocated and freed space Allocate: Increment pointer Free: Decrement pointer Stack Discussion OS uses stack for procedure call frames (local variables) main () { int A = 0; foo (A); printf( A: %d\n, A); } void foo (int Z) { int A = 2; Z = 5; printf( A: %d Z: %d\n, A, Z); } Advantages Keeps all free space contiguous Simple to implement Efficient at run time Not appropriate for all data structures 1

Heap Organization Definition: Allocate from any random location Memory consists of allocated areas and free areas (holes) Order of allocation and free is unpredictable 24 bytes Advantage 12bytes Works for all data structures 16 bytes Allocation can be slow 16 bytes End up with small chunks of free space Free Alloc Free Alloc Where to allocate 16 bytes? 12 bytes? 24 bytes?? A B Fragmentation Definition: Free memory that is too small to be usefully allocated External: Visible to allocator Internal: Visible to requester (e.g., if must allocate at some granularity) Goal: Minimize fragmentation Few holes, each hole is large Free space is contiguous Stack All free space is contiguous No fragmentation Heap How to allocate to minimize fragmentation? Heap Implementation Data structure: free list Linked list of free blocks, tracks memory not in use Header in each block size of block ptr to next block in list void *Allocate(x bytes) Choose block large enough for request (>= x bytes) Keep remainder of free block on free list Update list pointers and size variable Return pointer to allocated memory Free(ptr) Add block back to free list Merge adjacent blocks in free list, update ptrs and size variables Heap Allocation Policies Best fit Search entire list for each allocation Choose free block that most closely matches size of request Optimization: Stop searching if see exact match First fit Allocate first block that is large enough Rotating first fit (or Next fit ): Variant of first fit, remember place in list Start with next free block each time Worst fit Allocate largest block to request (most leftover space) 2

Heap Allocation Examples Scenario: Two free blocks of size 20 and 15 bytes Allocation stream: 10, 20 Best First Worst Allocation stream: 8, 12, 12 Best First Worst Buddy Allocation Fast, simple allocation for blocks of 2 n bytes [Knuth68] void *Allocate (k bytes) Raise allocation request to nearest s = 2 n Search free list for appropriate size Represent free list with bitmap Recursively divide larger free blocks until find block of size s Buddy block remains free Mark corresponding bits as allocated Free(ptr) Mark bits as free Recursively coalesce block with buddy, if buddy is free May coalesce lazily (later, in background) to avoid overhead Buddy Allocation Example Scenario: 1MB of free memory Request stream: Allocate 70KB, 35KB, 80KB Free 35KB, 80KB, 70KB Comparison of Allocation Strategies No optimal algorithm Fragmentation highly dependent on workload Best fit Tends to leave some very large holes and some very small holes Can t use very small holes easily First fit Tends to leave average sized holes Advantage: Faster than best fit Next fit used often in practice Buddy allocation Minimizes external fragmentation Disadvantage: Internal fragmentation when not 2^n request 3

Memory Allocation in Practice How is malloc() implemented? Data structure: Free lists Header for each element of free list pointer to next free block size of block magic number Where is header stored? What if remainder of block is smaller than header? Two free lists One organized by size Separate list for each popular, small size (e.g., 1 KB) Allocation is fast, no external fragmentation Second is sorted by address Use next fit to search appropriately Free blocks shuffled between two lists Freeing Memory C: Expect programmer to explicitly call free(ptr) Two possible problems Dangling pointers: Recycle storage that is still in-use Have two pointers to same memory, free one and use second foo_t *a = malloc(sizeof(foo_t)); foo_t *b = a; b->bar = 50; free(a); foo_t *c = malloc(sizeof(foo_t)); c->bar = 20; printf( b->bar: %d\n, b->bar); Memory leaks: Forget to free storage If lose pointer, can never free associated memory Okay in short jobs, not okay for OS or long-running servers foo_t *a = malloc(sizeof(foo_t)); foo_t *b = malloc(sizeof(foo_t)); b = a; Reference Counts Idea: Reference counts Track number of references to each memory chunk Increment count when new pointer references it Decrement count when pointer no longer references it When reference count = 0, free memory Examples Hard links in Unix echo Hi > file ln file new rm file cat new Smalltalk Circular data structures --> Memory leaks Garbage Collection Observation: To use data, must have pointer to it Without pointer, cannot access (or find) data Memory is free implicitly when no longer referenced Programmer does not call free() Approach When system needs more memory, free unreachable chunks Requirements Must be able to find all objects (referenced and not) Must be able to find all pointers to objects Strongly typed language Compiler cooperates by marking data type in memory Size of each object Which fields are pointers 4

Mark and Sweep Garbage Collection Pass 1: Mark all reachable data Start with all statically allocated and local (stack) variables Mark each data object as reachable Recursively mark all data objects can reach through pointers Pass 2: Sweep through all memory Examine each data object Free those objects not marked Advantages Works with circular data structures Simple for application programmers Often CPU-intensive (poor caching behavior too) Difficult to implement such that can execute job during g.c. Requires language support (Java, LISP) 5