Dynamic Memory Management! Goals of this Lecture!

Similar documents
Dynamic Memory Management

Dynamic Memory Management

CSC 1600 Memory Layout for Unix Processes"

Dynamic Memory Allocation

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

Optimizing Dynamic Memory Management

Dynamic Memory Allocation. Zhaoguo Wang

Dynamic Memory Allocation: Basic Concepts

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

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

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

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

Dynamic Memory Allocation: Basic Concepts

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

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

CS61C : Machine Structures

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

Dynamic Memory Allocation

10.1. CS356 Unit 10. Memory Allocation & Heap Management

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

Memory management. Johan Montelius KTH

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

Dynamic Memory Allocation

Dynamic Memory Allocation I Nov 5, 2002

Dynamic Memory Alloca/on: Basic Concepts

Dynamic Memory Allocation I

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

Lectures 13 & 14. memory management

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

Programming Language Implementation

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

ECE 598 Advanced Operating Systems Lecture 10

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

Class Information ANNOUCEMENTS

Dynamic Memory Alloca/on: Basic Concepts

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

Memory Management Basics

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

CS61C : Machine Structures

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

Run-time Environments

Run-time Environments

ECE 598 Advanced Operating Systems Lecture 12

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

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

Run-Time Environments/Garbage Collection

Dynamic Storage Allocation

Limitations of the stack

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

Review! Lecture 5 C Memory Management !

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

CS61C : Machine Structures

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Lecture 13: Garbage Collection

Run-time Environments -Part 3

Memory Management in C (Dynamic Strings) Personal Software Engineering

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Heap Management. Heap Allocation

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages

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

Lecture 8 Dynamic Memory Allocation

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

CSE351 Spring 2018, Final Exam June 6, 2018

Requirements, Partitioning, paging, and segmentation

Run-time Environments - 3

Garbage Collection (1)

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

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

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

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

Requirements, Partitioning, paging, and segmentation

CS61C : Machine Structures

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

Dynamic Memory Allocation

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

Secure Software Programming and Vulnerability Analysis

Deallocation Mechanisms. User-controlled Deallocation. Automatic Garbage Collection

Advanced Programming & C++ Language

CS61C Midterm Review on C & Memory Management

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Robust Memory Management Schemes

CS61C : Machine Structures

Operating System Labs. Yuanbin Wu

Automatic Memory Management

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

Intrusion Detection and Malware Analysis

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

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

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

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

Compiler Construction

Buffer overflow background

ANITA S SUPER AWESOME RECITATION SLIDES

Binding and Storage. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Compiler Construction

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

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

Transcription:

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++)! Design decisions for the K&R heap manager implementation! Circular linked-list of free blocks with a first fit allocation! Coalescing of adjacent blocks to create larger blocks! 2 1

Part 1:! What do malloc() and free() do?! 3 Memory Layout:! char* string = "hello"; int isize; char* f() { char* p; scanf("%d", &isize); p = malloc(isize); return p; Needed when required memory size is not known before the program runs! Text RoData Data BSS 4 2

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! 5 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(); Object Foo() is never used again! 6 3

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 can lead 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! 7 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 in many/most cases! No unexpected pauses! More efficient use of memory! Disadvantages! More complex for the programmer! Subtle memory-related bugs! Security vulnerabilities in the (buggy) code! 8 4

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(1); free(p); putchar(*p); May print nonsense character. 9 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! void f(void) { char *s; s = malloc(5); return; Eventually, malloc() returns NULL int main(void) { while (1) f(); return ; 1 5

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(1); free(p); q = malloc(1); free(p); Might free the space allocated to q! 11 malloc() and free() Challenges! malloc() may ask for arbitrary number of bytes! Memory may be allocated & freed in different order! Cannot reorder requests to improve performance! 12 6

: Dynamic Memory! 13 : Dynamic Memory! p2 14 7

: Dynamic Memory! p2 p3 15 : Dynamic Memory! p2 p3 16 8

: Dynamic Memory! p2 p3 p4 17 : Dynamic Memory! p2 p3 p4 18 9

: Dynamic Memory! p5, p2 p3 p4 19 : Dynamic Memory! p5, p2 p3 p4 2 1

: Dynamic Memory! p5, p2 p3 p4 21 : Dynamic Memory! p5, p2 p3 p4 22 11

Part 2:! How do malloc() and free() work?! 23 The Program Break! The program break marks the end of the heap, and in theory, the stack can grow to it.!!!! FFFFFFFF program break! In theory, this limits the maximum stack size! program break! FFFFFFFF 24 12

Acquiring Memory! Q: How does malloc() acquire heap memory?! A: Moves the program break downward via sbrk() or brk()system call! void *sbrk(intptr_t increment); Increment the program break by the specified amount. Calling the function with an increment of returns the current location of the program break. Return if successful and -1 otherwise.! Beware: On Linux contains a known bug; should call only with argument.! int brk(void *newbreak); Move the program break to the specified address. Return if successful and -1 otherwise.! 25 Using Memory! Q: Having acquired heap memory, how do malloc() and free() manipulate it?! A: Many different approaches; an introduction!! 26 13

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! 27 Keeping Track of Free Blocks! Maintain a list 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! When necessary, call brk() to ask OS for additional memory, and create a new large block! 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 28 14

Need to Minimize Fragmentation! Internal fragmentation! Allocated block is larger than malloc() requested! E.g., malloc() imposes a minimum size (e.g., 64 bytes)! 33 External fragmentation! Enough free memory exists, but no block is big enough! E.g., malloc() asks for 128 contiguous bytes! 64 64 64 29 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! 3 15

Allocate Memory in Multiples of Base Size! Allocate memory in multiples of a base size! Avoid maintaining very tiny free blocks! Align memory on size of largest data type (e.g., double)! 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! 16 16 5 31 Linked List of Free Blocks! Linked list of free blocks! malloc() allocates a big-enough block! Allocated free() adds newly-freed block to the list! Newly freed 32 16

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 33 Splitting an Oversized Free Block! Simple case: perfect fit! malloc() asks for 128 bytes, free block has 128 bytes! Simply remove the free block from the list! 48 32 128 64 256 Complex case: splitting the block! malloc() asks for 64 bytes, free block has 128 bytes! 48 32 64 64 256 64 34 17

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 64 256 35 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 36 18

Coalescing Adjacent Free Blocks! When inserting a block in the free list! Look left and look right for neighboring free blocks! In use In use Left In use Right In use In use 37 Conclusion! 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! 38 19