Dynamic Memory Allocation

Similar documents
Dynamic Memory Allocation I Nov 5, 2002

Dynamic Memory Allocation I

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt

Dynamic Memory Allocation

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Dynamic Memory Allocation: Basic Concepts

Dynamic Memory Allocation: Basic Concepts

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th

Dynamic Memory Allocation. Basic Concepts. Computer Organization 4/3/2012. CSC252 - Spring The malloc Package. Kai Shen

Memory Allocation. Copyright : University of Illinois CS 241 Staff 1

Dynamic Memory Alloca/on: Basic Concepts

CS 33. Storage Allocation. CS33 Intro to Computer Systems XXVII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Dynamic Memory Alloca/on: Basic Concepts

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

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

Dynamic Memory Allocation

Dynamic Memory Allocation

Memory Allocation II. CSE 351 Autumn Instructor: Justin Hsia

Memory Allocation II. CSE 351 Autumn Instructor: Justin Hsia

CS 153 Design of Operating Systems

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Dynamic Memory Management

Dynamic Memory Allocation

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Foundations of Computer Systems

Dynamic Memory Management

Binghamton University Dynamic Memory Alloca/on

Princeton University. Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management

Dynamic Memory Management! Goals of this Lecture!

ANITA S SUPER AWESOME RECITATION SLIDES

Foundations of Computer Systems

CS61C : Machine Structures

Recitation #12 Malloc Lab - Part 2. November 14th, 2017

Princeton University Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management

Dynamic Memory Allocation. Zhaoguo Wang

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

Dynamic Memory Allocation II October 22, 2008

Optimizing Dynamic Memory Management

10.1. CS356 Unit 10. Memory Allocation & Heap Management

Today. Dynamic Memory Allocation: Advanced Concepts. Explicit Free Lists. Keeping Track of Free Blocks. Allocating From Explicit Free Lists

Internal Fragmentation

Review! Lecture 5 C Memory Management !

CS61C : Machine Structures

Recitation #11 Malloc Lab. November 7th, 2017

CS 153 Design of Operating Systems

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

Carnegie Mellon. Malloc Boot Camp. Stan, Nikhil, Kim

ECE 598 Advanced Operating Systems Lecture 10

Memory management. Johan Montelius KTH

CS61C : Machine Structures

Engine Support System. asyrani.com

Dynamic Memory Allocation: Advanced Concepts

ECE 598 Advanced Operating Systems Lecture 12

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Dynamic Memory Allocation: Advanced Concepts

Lecture 8 Dynamic Memory Allocation

Memory Allocation III

Lectures 13 & 14. memory management

Dynamic Memory Allocation: Advanced Concepts

Heap Management. Heap Allocation

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

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

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

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

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

CS61C : Machine Structures

Secure Software Programming and Vulnerability Analysis

Memory Management. CS449 Fall 2017

Lecture 13: Garbage Collection

Recitation 10: Malloc Lab

CSE 351, Spring 2010 Lab 7: Writing a Dynamic Storage Allocator Due: Thursday May 27, 11:59PM

Dynamic Memory Allocation. CS 351: Systems Programming Michael Saelee

Memory Allocation III CSE 351 Spring (original source unknown)

2/9/18. Secure Coding. CYSE 411/AIT681 Secure Software Engineering. Agenda. Dynamic Memory Interface. Dynamic Memory Interface

Run-time Environments - 3

Operating System Labs. Yuanbin Wu

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

Requirements, Partitioning, paging, and segmentation

Dynamic Memory Alloca/on: Advanced Concepts

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

CS 213, Fall 2002 Malloc Lab: Writing a Debugging Dynamic Storage Allocator Assigned: Fri Nov. 1, Due: Tuesday Nov. 19, 11:59PM

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

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

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

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

CS61C : Machine Structures

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

HW 3: Malloc CS 162. Due: Monday, March 28, 2016

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

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory.

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Requirements, Partitioning, paging, and segmentation

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

CS61C : Machine Structures

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

Run-time Environments -Part 3

ECE454, Fall 2014 Homework3: Dynamic Memory Allocation Assigned: Oct 9th, Due: Nov 6th, 11:59PM

Memory Management. Dr. Yingwu Zhu

CMSC 313 Spring 2010 Exam 3 May 17, 2010

Transcription:

Dynamic Memory Allocation CS61, Lecture 10 Prof. Stephen Chong October 4, 2011

Announcements 1/2 Assignment 4: Malloc Will be released today May work in groups of one or two Please go to website and enter your group by Sunday 11:59PM Every group must do this (i.e., even if you are working individually) Two deadlines: Design checkpoint: Thursday October 13, 10pm Final submission: Thursday October 20, 11:59pm Encourage you to use version control Assignment 3 (Buffer bomb) due Thursday Stephen Chong, Harvard University 2

Announcements 2/2 Give us feedback on when you d like office hours http://tinyurl.com/689seas Link posted on website Stephen Chong, Harvard University 3

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 4

Harsh Reality: Memory Matters! Memory is not unlimited! It must be allocated and managed Many applications are memory dominated Especially those based on complex, graph algorithms Memory referencing bugs especially pernicious Effects are distant in both time and space Memory performance is not uniform Cache and virtual memory effects can greatly affect program performance Adapting program to characteristics of memory system can lead to major speed improvements Stephen Chong, Harvard University 5

A process's view of memory Process not allowed to read or write this region 0xffffffff 0xc0000000 %esp Process address space OS memory User stack Dynamically allocated memory 0x40000000 Shared libraries Heap (used by malloc) Global vars Program code 0x08048000 0x00000000 Read/write segment.data,.bss Read-only segment.text,.rodata unused Stephen Chong, Harvard University 6

The heap The heap is the region of a program's memory used for dynamic allocation. Program can allocate and free blocks of memory within the heap. Heap Allocated block (4 bytes) Free block (3 bytes) Free byte Allocated byte Stephen Chong, Harvard University 7

Free blocks, and allocated blocks Heap starts out as a single big free block of some fixed size (say a few MB) Program may request memory, which splits up the the free space. Program may free up some memory, which increases the free space Over time the heap will contain a mixture of free and allocated blocks. Heap may need to grow in size (but typically never shrinks) Program can grow the heap if it is too small to handle an allocation request. On UNIX, the sbrk() system call is used to expand the size of the heap................... Stephen Chong, Harvard University 8

Dynamic Memory Management How do we decide when do expand the heap (using sbrk())? How do we manage allocating and freeing bytes on the heap? There are two broad classes of memory management schemes: Explicit memory management Application code responsible for both explicitly allocating and freeing memory. Example: malloc() and free() Implicit memory management Application code can allocate memory, but does not explicitly free memory Rather, rely on garbage collection to clean up memory objects no longer in use Used in languages like Java, Python, OCaml Stephen Chong, Harvard University 9

Malloc Package #include <stdlib.h> void *malloc(size_t size) If successful: Returns a pointer to a memory block of at least size bytes If size == 0, returns NULL If unsuccessful: returns NULL. void free(void *p) Returns the block pointed at by p to pool of available memory p must come from a previous call to malloc or realloc. void *realloc(void *p, size_t size) Changes size of block p and returns pointer to new block. Contents of new block unchanged up to min of old and new size. Stephen Chong, Harvard University 10

Allocation Examples Heap p1 = malloc(4) p2 = malloc(5) p3 = malloc(6) free(p2) p4 = malloc(2) Stephen Chong, Harvard University 11

Constraints Application code must obey following constraints: Allowed to issue arbitrary sequence of allocation and free requests Free requests must correspond to an allocated block Memory management code must obey following constraints: Can t control number or size of requested blocks Must respond immediately to all allocation requests i.e., can t reorder or buffer requests Must allocate blocks from free memory i.e., can only place allocated blocks in free memory Must align blocks so they satisfy all alignment requirements Can t mess around with allocated memory Can only manipulate and modify free memory Can t move the allocated blocks once they are allocated (i.e., compaction is not allowed) Stephen Chong, Harvard University 12

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 13

What do we want? Want our memory management to be: Fast Minimize overhead of allocation and deallocation operations. Efficient Don t waste memory space Stephen Chong, Harvard University 14

Performance Goals: Allocation overhead Want our memory allocator to be fast! Minimize the overhead of both allocation and deallocation operations. One useful metric is throughput: Given a series of allocate or free requests Maximize the number of completed requests per unit time Example: 5,000 malloc calls and 5,000 free calls in 10 seconds Throughput is 1,000 operations/second. Stephen Chong, Harvard University 15

Performance Goals: Memory Utilization Allocators rarely do a perfect job of managing memory. Usually there is some waste involved in the process. Examples of waste... Extra metadata or internal structures used by the allocator itself (example: Keeping track of where free memory is located) Chunks of heap memory that are unallocated (fragments) We define memory utilization as... The total amount of memory allocated to the application divided by the total heap size Ideally, we'd like utilization to be to 100% In practice this is not possible, but want to be as close as possible Allocated memory Unallocated fragments Metadata Heap Stephen Chong, Harvard University 16

Conflicting performance goals High throughput and good utilization are difficult to achieve simultaneously. A fast allocator may not be efficient in terms of memory utilization. Faster allocators tend to be sloppier with their memory usage. Likewise, a space-efficient allocator may not be very fast To keep track of memory waste (i.e., tracking fragments), the allocation operations generally take longer to run. Trick is to balance these two conflicting goals. Stephen Chong, Harvard University 17

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Alignment Stephen Chong, Harvard University 18

Internal Fragmentation Poor memory utilization caused by fragmentation. Comes in two forms: internal and external fragmentation Internal fragmentation Internal fragmentation is the difference between block size and payload size. block Internal fragmentation payload Internal fragmentation Caused by overhead of maintaining heap data structures, padding for alignment purposes, or the policy used by the memory allocator Example: Say the allocator always rounds up to next highest power of 2 when allocating blocks. So malloc(1025) will actually allocate 2048 bytes of heap space! Stephen Chong, Harvard University 19

External Fragmentation Occurs when there is enough aggregate heap memory, but no single free block is large enough to satisfy a given request. p1 = malloc(4) p2 = malloc(5) p3 = malloc(6) free(p2) p4 = malloc(6) No free block big enough! Stephen Chong, Harvard University 20

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 21

Free block list management How do we know how much memory to free just given a pointer? How do we keep track of the free blocks? What do we do with the extra space when allocating a memory block that is smaller than the free block it is placed in? How do we pick which free block to use for allocation? Stephen Chong, Harvard University 22

Knowing how much to free Standard method Keep the length of a block in a header preceding the block. Requires an extra word for every allocated block p = malloc(4) p 5 free(p) header (address p-1) data Stephen Chong, Harvard University 23

Keeping Track of Free Blocks One of the biggest jobs of an allocator is knowing where the free memory is. Affects throughput and utilization Many approaches to free block management. Today, we will talk about three techniques Implicit free lists Explicit free lists Segregated free lists There are other approaches Stephen Chong, Harvard University 24

Implicit free list Idea: Each block contains a header with some extra information. Allocated bit indicates whether block is allocated or free. Size field indicates entire size of block (including the header) Trick: Allocation bit is just the high-order bit of the size word For this lecture, assume header size is 1 byte. Makes later pictures easier to understand. This means the block size is only 7 bits, so max. block size is 127 bytes (2 7-1). Clearly a real implementation would want to use a larger header (e.g., 4 bytes). a size payload or free space optional padding a = 1: block is allocated a = 0: block is free size: block size payload: application data Stephen Chong, Harvard University 25

Examples 0x84 4 bytes total size payload 0x84 in binary: 1000 0100 allocated = 1 size = 000 0100 = 0x4 = 4 bytes 15 bytes total size 0x0f payload 0x0f in binary: 0000 1111 allocated = 0 size = 000 1111 = 0xf = 15 bytes Stephen Chong, Harvard University 26

Implicit free list Implicit list 5 4 6 2 Free Allocated Free Allocated No explicit structure tracking location of free/allocated blocks. Rather, the size word (and allocated bit) in each block form an implicit block list How do we find a free block in the heap? Start scanning from the beginning of the heap. Traverse each block until (a) we find a free block and (b) the block is large enough to handle the request. This is called the first fit strategy. Stephen Chong, Harvard University 27

Implicit List: Finding a Free Block First fit strategy: Search list from beginning, choose first free block that fits Can take linear time in total number of blocks (allocated and free) In practice it can cause splinters at beginning of list Next fit strategy: Like first-fit, but search list from location of end of previous search Research suggests that fragmentation is worse than first-fit Best fit strategy: Search the list, choose the free block with the closest size that fits Keeps fragments small usually helps fragmentation Runs slower than first- or next-fit, since the entire list must be searched each time Stephen Chong, Harvard University 28

Implicit List: Allocating in Free Block Splitting free blocks Since allocated space might be smaller than free space, we may need to split the free block that we're allocating within E.g., malloc(3) 2 4 6 2 p void addblock(ptr_t p, int len) { int oldsize = *p; // Get old size of free block *p = len 0x80; // Set new size + alloc bit if (len < oldsize) *(p+len) = oldsize - len; // Set size of remaining } // part of free block addblock(p, 4) 2 4 4 2 2 Stephen Chong, Harvard University 29

Implicit List: Freeing a Block Simplest implementation: Simply clear the allocated bit in the header /* Here, p points to the block header. */ /* This sets the high-order bit to 0. */ void free_block(ptr_t p) { *p = *p & 0x7f; } free(p+1) 4 4 4 2 2 p 4 4 4 2 2 Stephen Chong, Harvard University 30

Implicit List: Freeing a Block Simplest implementation: Simply clear the allocated bit in the header /* Here, p points to the block header. */ /* This sets the high-order bit to 0. */ void free_block(ptr_t p) { *p = *p & ~0x80; } But can lead to false fragmentation free(p+1) 4 4 4 2 2 p 4 4 4 2 2 malloc(5) There is enough free space, but the allocator won t be able to find it! Stephen Chong, Harvard University 31

Implicit List: Coalescing Coalesce with adjacent block(s) if they are free void free_block(ptr_t p) { *p = *p & 0x7f; // Clear allocated bit next = p + *p; // Find next block if ((*next & 0x80) == 0) *p = *p + *next; // Add to this block if } // next is also free free(p+1) 4 4 4 2 2 p 4 4 6 2 This is coalescing with the next free block. How would we coalesce with the previous free block? Stephen Chong, Harvard University 32

Implicit List: Bidirectional Coalescing Boundary tags [Knuth73] Also maintain the size/allocated word at end of free blocks (a footer) Pointers in headers 4 4 4 4 6 6 4 4 Pointers in footers Allows us to traverse the block list backwards, but requires extra space Header a size payload and padding Boundary tag (footer) a size a = 1: block is allocated a = 0: block is free size: total block size payload: application data Important and general technique! Stephen Chong, Harvard University 33

Constant Time Coalescing Case 1 Case 2 Case 3 Case 4 block being freed allocated allocated allocated free free allocated free free Stephen Chong, Harvard University 34

Constant Time Coalescing (Case 1) m1 1 m1 1 n 1 n 1 m2 1 m2 1 m1 1 m1 1 n 0 n 0 m2 1 m2 1 Stephen Chong, Harvard University 35

Constant Time Coalescing (Case 2) m1 1 m1 1 n 1 m1 1 m1 1 n+m2 0 n 1 m2 0 m2 0 n+m2 0 Stephen Chong, Harvard University 36

Constant Time Coalescing (Case 3) m1 0 n+m1 0 m1 0 n 1 n 1 m2 1 m2 1 n+m1 0 m2 1 m2 1 Stephen Chong, Harvard University 37

Constant Time Coalescing (Case 4) m1 0 n 0 m1 0 n 1 n 1 m2 0 m2 0 n 0 Stephen Chong, Harvard University 38

Implicit Lists: Summary Implementation: Very simple. Allocation cost: Linear time worst case Free cost: Constant time, even with coalescing Memory usage: Depends on placement policy First fit, next fit, or best fit Not used in practice for malloc/free because of linear time allocation. The concepts of splitting and boundary tag coalescing are general to all allocators. Stephen Chong, Harvard University 39

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 40

Explicit Free Lists Use an explicit data structure to track the free blocks Just a doubly-linked list. No pointers to or from allocated blocks: Can put the pointers into the payload! Still need boundary tags, in order to perform free block coalescing. A B C Forward links 4 4 4 4 6 6 4 4 4 4 Back links Stephen Chong, Harvard University 41

Explicit Free Lists Note that free blocks need not be linked in the same order they appear in memory! Free blocks can be chained together in any order. A B C Forward links 4 4 4 4 6 6 4 4 4 4 Back links Stephen Chong, Harvard University 42

Allocation using an explicit free list Before: p = malloc(size); After: split 2nd free block p Stephen Chong, Harvard University 43

Deallocation with an explicit free list Same idea as previously Step 1: Mark block as free Step 2: Coalesce adjacent free blocks Step 3: Insert free block into the free list Where in the free list do we put a newly freed block? LIFO (last-in-first-out) policy Insert freed block at the beginning of the free list Simple and constant time Address-ordered policy Insert freed blocks so that free list blocks are always in address order Con: requires search Pro: studies suggest fragmentation is lower than LIFO Stephen Chong, Harvard University 44

Freeing With a LIFO Policy (Case 1) Before: free(p) Root Insert the freed block at the root of the free block list After: Root Stephen Chong, Harvard University 45

Freeing With a LIFO Policy (Case 2) Before: free(p) Root Splice out predecessor block, coalesce both memory blocks and insert the new block at the root of the list After: Root Stephen Chong, Harvard University 46

Freeing With a LIFO Policy (Case 3) Before: free(p) Root Splice out successor block, coalesce both memory blocks and insert the new block at the root of the list After: Root Stephen Chong, Harvard University 47

Freeing With a LIFO Policy (Case 4) Before: free(p) Root Splice out predecessor and successor blocks, coalesce all 3 memory blocks and insert the new block at the root of the list After: Root Stephen Chong, Harvard University 48

Explicit List Summary Comparison to implicit list: Allocation is linear time in number of free blocks Implicit list allocation is linear time in the number of total blocks Slightly more complicated allocate and free since need to splice blocks in and out of the list Need some extra space for the links 2 extra words needed for each free block But these can be stored in the payload, since only needed for free blocks. Stephen Chong, Harvard University 49

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 50

Segregated List (seglist) Allocators Use a different free list for blocks of different sizes! 1-2 3 4 5-8 9-inf Often have separate size class for every small size (4,5,6, ) For larger sizes typically have a size class for each power of 2 Stephen Chong, Harvard University 51

Seglist Allocator To allocate a block of size n: Determine correct free list to use Search that free list for block of size m n If an appropriate block is found: Split block and place fragment on appropriate list If no block is found, try next larger class Repeat until block is found If no free block is found: Request additional heap memory from OS (using sbrk() system call) Allocate block of n bytes from this new memory Place remainder as a single free block in largest size class. Stephen Chong, Harvard University 52

Freeing with Seglist To free a block: Mark block as free Coalesce (if needed) Place free block on appropriate sized list Stephen Chong, Harvard University 53

Seglist advantages Advantages of seglist allocators Higher throughput Faster to find appropriate sized block: Look in the right list. Better memory utilization First-fit search of segregated free list approximates a best-fit search of entire heap. Extreme case: Giving each size its own segregated list is equivalent to best-fit. Stephen Chong, Harvard University 54

Topics for today Dynamic memory allocation Implicit vs. explicit memory management Performance goals Fragmentation Free block list management Implicit free list Explicit free list Segregated lists Tradeoffs Stephen Chong, Harvard University 55

Allocation Policy Tradeoffs Data structure for free lists Implicit lists, explicit lists, segregated lists Other structures possible, e.g.explicit free blocks in binary tree, sorted by size Placement policy: First fit, next fit, or best fit Best fit has higher overhead, but less fragmentation. Splitting policy: When do we split free blocks? Splitting leads to more internal fragmentation, since each block needs its own header. Coalescing policy: When do we coalesce free blocks? Immediate coalescing: Coalesce each time free is called Deferred coalescing: Improve free performance by deferring coalescing until needed. E.g., While scanning the free list for malloc(), or when external fragmentation reaches some threshold. Stephen Chong, Harvard University 56

Topics for next time Allocation requirements Common memory bugs Implicit memory management: Garbage collection Stephen Chong, Harvard University 57