Dynamic Memory Management

Slides:



Advertisements
Similar presentations
Introduction to Memory Management. 2 General Structure of Run-Time Memory.
Advertisements

Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
Dynamic Memory Allocation I Topics Simple explicit allocators Data structures Mechanisms Policies CS 105 Tour of the Black Holes of Computing.
Dynamic Memory Allocation I Topics Basic representation and alignment (mainly for static memory allocation, main concepts carry over to dynamic memory.
Chris Riesbeck, Fall 2007 Dynamic Memory Allocation Today Dynamic memory allocation – mechanisms & policies Memory bugs.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
KERNEL MEMORY ALLOCATION Unix Internals, Uresh Vahalia Sowmya Ponugoti CMSC 691X.
1 Memory Allocation Professor Jennifer Rexford COS 217.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 Optimizing Malloc and Free Professor Jennifer Rexford COS 217 Reading: Section 8.7 in K&R book
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
CPSC 388 – Compiler Design and Construction
CS 1114: Data Structures – memory allocation Prof. Graeme Bailey (notes modified from Noah Snavely, Spring 2009)
CS 1114: Data Structures – Implementation: part 1 Prof. Graeme Bailey (notes modified from Noah Snavely, Spring 2009)
Lab 3: Malloc Lab. “What do we need to do?”  Due 11/26  One more assignment after this one  Partnering  Non-Honors students may work with one other.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Memory Management Memory Areas and their use Memory Manager Tasks:
1 Optimizing Malloc and Free Professor Jennifer Rexford
CS61C L06 C Memory Management (1) Garcia, Spring 2008 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C :
C and Data Structures Baojian Hua
CS61C L06 C Memory Management (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
Linked lists and memory allocation Prof. Noah Snavely CS1114
1 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
Memory Layout C and Data Structures Baojian Hua
1 Dynamic Memory Management. 2 What’s worse?  50% of instructions/data are cache misses (fetched from RAM)  1% of instructions/data are page faults.
The memory allocation problem Define the memory allocation problem Memory organization and memory allocation schemes.
Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is a heap? What are best-fit, first-fit, worst-fit, and.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Memory Management. Memory  Commemoration or Remembrance.
1 Memory Management Basics. 2 Program P Basic Memory Management Concepts Address spaces Physical address space — The address space supported by the hardware.
1 Advanced Memory Management Techniques  static vs. dynamic kernel memory allocation  resource map allocation  power-of-two free list allocation  buddy.
1 Dynamic Memory Allocation: Basic Concepts. 2 Today Basic concepts Implicit free lists.
11/26/2015IT 3271 Memory Management (Ch 14) n Dynamic memory allocation Language systems provide an important hidden player: Runtime memory manager – Activation.
CS 241 Discussion Section (11/17/2011). Outline Review of MP7 MP8 Overview Simple Code Examples (Bad before the Good) Theory behind MP8.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Consider Starting with 160 k of memory do: Starting with 160 k of memory do: Allocate p1 (50 k) Allocate p1 (50 k) Allocate p2 (30 k) Allocate p2 (30 k)
Carnegie Mellon 1 Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition Dynamic Memory Allocation: Basic Concepts :
CS 241 Discussion Section (12/1/2011). Tradeoffs When do you: – Expand Increase total memory usage – Split Make smaller chunks (avoid internal fragmentation)
Lecture 7 Page 1 CS 111 Summer 2013 Dynamic Domain Allocation A concept covered in a previous lecture We’ll just review it here Domains are regions of.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
Dynamic Memory Management Jennifer Rexford 1. 2 Goals of this Lecture Dynamic memory management techniques Garbage collection by the run-time system (Java)
CSE 220 – C Programming malloc, calloc, realloc.
CSC 533: Programming Languages Spring 2016
Chapter 17 Free-Space Management
Instructor: Phil Gibbons
Section 10: Memory Allocation Topics
Memory Management Memory Areas and their use Memory Manager Tasks:
CSC 533: Programming Languages Spring 2015
Storage 18-May-18.
Dynamic Domain Allocation
Storage Management.
Memory Management Memory Areas and their use Memory Manager Tasks:
Dynamic Memory Allocation: Basic Concepts CS220: Computer Systems II
The Hardware/Software Interface CSE351 Winter 2013
Optimizing Malloc and Free
Storage.
Lecturer SOE Dan Garcia
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation: Basic Concepts /18-213/14-513/15-513: Introduction to Computer Systems 19th Lecture, October 30, 2018.
Optimizing Dynamic Memory Management
Memory Management (1).
Dynamic Memory Allocation: Basic Concepts CSCI 380: Operating Systems
Memory Management Memory Areas and their use Memory Manager Tasks:
CS703 - Advanced Operating Systems
CSC 533: Programming Languages Spring 2019
Presentation transcript:

Dynamic Memory Management Professor Jennifer Rexford http://www.cs.princeton.edu/~jrex

Goals of Today’s Lecture Dynamic memory management Garbage collection by the run-time system (Java) Manual deallocation by the programmer (C, C++) Challenges of manual deallocation Arbitrary request sizes in an arbitrary order Complex evolution of heap as a program runs Design decisions for the “K&R” implementation Circular linked-list of free blocks with a “first fit” allocation Coalescing of adjacent blocks to create larger blocks

Needed when required memory size is not known before the program runs Memory Layout: Heap char* string = “hello”; int iSize; char* f() { char* p; scanf(“%d”, &iSize); p = malloc(iSize); return p; } Text RoData Data BSS Heap Needed when required memory size is not known before the program runs Stack

Allocating & Deallocating Memory Dynamically allocating memory Programmer explicitly requests space in memory Space is allocated dynamically on the heap E.g., using “malloc” in C, and “new” in Java Dynamically deallocating memory Must reclaim or recycle memory that is never used again To avoid (eventually) running out of memory “Garbage” Allocated block in heap that will not be accessed again Can be reclaimed for later use by the program

Option #1: Garbage Collection Run-time system does garbage collection (Java) Automatically determines objects that can’t be accessed And then reclaims the resources used by these objects Object x = new Foo(); Object y = new Bar(); x = new Quux(); if (x.check_something()) { x.do_something(y); } System.exit(0); Object Foo() is never used again!

Challenges of Garbage Collection Detecting the garbage is not always easy “if (complex_function(y)) x = Quux();” Run-time system cannot collect all of the garbage Detecting the garbage introduces overhead Keeping track of references to objects (e.g., counter) Scanning through accessible objects to identify garbage Sometimes walking through a large amount of memory Cleaning the garbage leads to bursty delays E.g., periodic scans of the objects to hunt for garbage Leading to unpredictable “freeze” of the running program Very problematic for real-time applications … though good run-time systems avoid long freezes

Option #2: Manual Deallocation Programmer deallocates the memory (C and C++) Manually determines which objects can’t be accessed And then explicitly returns the resources to the heap E.g., using “free” in C or “delete” in C++ Advantages Lower overhead No unexpected “pauses” More efficient use of memory Disadvantages More complex for the programmer Subtle memory-related bugs Security vulnerabilities in the (buggy) code

Manual Deallocation Can Lead to Bugs Dangling pointers Programmer frees a region of memory … but still has a pointer to it Dereferencing pointer reads or writes nonsense values int main(void) { char *p; p = malloc(10); … free(p); putchar(*p); } May print nonsense character.

Manual Deallocation Can Lead to Bugs Memory leak Programmer neglects to free unused region of memory So, the space can never be allocated again Eventually may consume all of the available memory Eventually, malloc() returns NULL void f(void) { char *s; s = malloc(50); return; } int main(void) { while (1) f(); return 0; Dereferencing a NULL pointer typically causes a seg-fault. This program would just keep running, but consume every more memory, and push other processes out of main memory, making the whole system sluggish.

Manual Deallocation Can Lead to Bugs Double free Programmer mistakenly frees a region more than once Leading to corruption of the heap data structure … or premature destruction of a different object int main(void) { char *p, *q; p = malloc(10); … free(p); q = malloc(10); } Might free the space allocated to q!

Challenges for Malloc and Free Malloc() may ask for an arbitrary number of bytes Memory may be allocated & freed in different order Cannot reorder requests to improve performance char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5);

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); } Heap Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p2 } Heap Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p2 } p3 Heap Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p2 } p3 Heap Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p2 } p3 Heap p4 Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p2 } p3 Heap p4 Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p5, p2 } p3 Heap p4 Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p5, p2 } p3 Heap p4 Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p5, p2 } p3 Heap p4 Stack 0xffffffff

Heap: Dynamic Memory #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); Heap p1 char *p1 = malloc(3); char *p2 = malloc(1); char *p3 = malloc(4); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p5, p2 } p3 Heap p4 Stack 0xffffffff

Goals for Malloc and Free Maximizing throughput Maximize number of requests completed per unit time Need both malloc() and free() to be fast Maximizing memory utilization Minimize the amount of wasted memory Need to minimize size of data structures Strawman #1: free() does nothing Good throughput, but poor memory utilization Strawman #2: malloc() finds the “best fit” Good memory utilization, but poor throughput

Keeping Track of Free Blocks Maintain a collection of free blocks of memory Allocate memory from one of the blocks in the free list Deallocate memory by returning the block to the free list Ask the OS for additional block when more are needed Design questions How to keep track of the free blocks in memory? How to choose an appropriate free block to allocate? What to do with the left-over space in a free block? What to do with a block that has just been freed? free free free

Need to Minimize Fragmentation Internal fragmentation Allocated block is larger than malloc() requested E.g., malloc() imposes a minimum size (e.g., 64 bytes) External fragmentation Enough free memory exists, but no block is big enough E.g., malloc() asks for 128 contiguous bytes 33 Avoiding internal fragmentation: probably want a range of block sizes Avoiding external fragmentation: need malloc() to be smart in selecting a good fit 64 64 64

Simple “K&R-Like” Approach Memory allocated in multiples of a base size E.g., 16 bytes, 32 bytes, 48 bytes, … Linked list of free blocks Malloc() and free() walk through the list to allocate and deallocate Malloc() allocates the first big-enough block To avoid sequencing further through the list Malloc() splits the free block To allocate what is needed, and leave the rest available Linked list is circular To be able to continue where you left off Linked list in the order the blocks appear in memory To be able to “coalesce” neighboring free blocks

Allocate Memory in Multiples of Base Size Allocate memory in multiples of a base size To avoid maintaining very tiny free blocks To align memory on size of largest data type (e.g., long) Requested size is “rounded up” Allocation in units of base_size Round:(nbytes + base_size – 1)/base_size Example: Suppose nbytes is 37 And base_size is 16 bytes Then (37 + 16 – 1)/16 is 52/16 which rounds down to 3 Downside: some internal fragmentation… 16 16 5

Linked List of Free Blocks Malloc() allocates a big-enough block Free() adds newly-freed block to the list Allocated Newly freed

“First-Fit” Allocation Handling a request for memory (e.g., malloc) Find a free block that satisfies the request Must have a “size” that is big enough, or bigger Simplest approach: first fit Sequence through the linked list Stop upon encountering a “big enough” free block Example: request for 64 bytes First-fit algorithm stops at the 128-byte block 48 32 128 64 256

Splitting an Oversized Free Block Simple case: perfect fit Malloc() asks for 128 bytes, and free block has 128 bytes Simply remove the free block from the list Complex case: splitting the block Malloc() asks for 64 bytes, and free block has 128 bytes 48 32 128 64 256 48 32 64 256 64 64

Circular Linked List of Free Blocks Advantages of making free list a circular list Any element in the list can be the beginning Don’t have to handle the “end” of the list as special Performance optimization Make the head be where last block was found More likely to find “big enough” blocks later in the list new head 48 32 64 256 64

Maintaining Free Blocks in Order Keep list in order of increasing addresses Makes it easier to coalesce adjacent free blocks Though, makes calls to free() more expensive Need to insert the newly-freed block in the right place Free list In use In use In use

Coalescing Adjacent Free Blocks When inserting a block in the free list “Look left” and “look right” for neighboring free blocks In use “Left” “Right” In use In use

An Implementation Challenge Need information about each free block Starting address of the block of memory Length of the free block Pointer to the next block in the free list Where should this information be stored? Number of free blocks is not known in advance So, need to store the information on the heap But, wait, this code is what manages the heap!!! Can’t call malloc() to allocate storage for this information Can’t call free() to relinquish the storage, either

Store Information in the Free Block Store the information directly in the free block Since the memory isn’t being used for anything anyway And allows data structure to grow and shrink as needed Every free block has a header Size of the free block Pointer to (i.e., address of) the next free block Challenge: programming outside the type system size

Conclusions Elegant simplicity of K&R malloc and free Simple header with pointer and size in each free block Simple circular linked list of free blocks Relatively small amount of code (~25 lines each) Limitations of K&R functions in terms of efficiency Malloc requires scanning the free list To find the first free block that is big enough Free requires scanning the free list To find the location to insert the to-be-freed block