Page 1. Memory Allocation and Usage CSE 361S. Different free lists for different size classes

Similar documents
Keeping Track of Free Blocks The course that gives CMU its Zip! Dynamic Memory Allocation II Nov 7, Allocating From Explicit Free Lists

Allocator Basics. Dynamic Memory Allocation in the Heap (malloc and free) Allocator Goals: malloc/free. Internal Fragmentation

Dynamic Memory Allocation II October 22, 2008

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

Internal Fragmentation

Outlines. Dynamic Memory Dynamic Memory Dynamic Memory The malloc Package. malloc Example

Dynamic Memory Allocation: Advanced Concepts

Dynamic Memory Allocation: Advanced Concepts

CS 153 Design of Operating Systems

520 Principles of Programming Languages. Memory Management. Memory Management... 35: Garbage Collection

Dynamic Memory Allocation

Memory Allocation III CSE 351 Spring (original source unknown)

Outline. Tiling, formally. Expression tile as rule. Statement tiles as rules. Function calls. CS 412 Introduction to Compilers

Mid-term exam. Scores. Fall term 2012 KAIST EE209 Programming Structures for EE. Thursday Oct 25, Student's name: Student ID:

Memory Allocation II. CSE 351 Autumn Instructor: Justin Hsia

Dynamic Memory Alloca/on: Advanced Concepts

Outline CS 412/413. Function calls. Stack layout. Tiling a call. Two translations

CPSC 213. Polymorphism. Introduction to Computer Systems. Readings for Next Two Lectures. Back to Procedure Calls

In the last lecture, we discussed how valid tokens may be specified by regular expressions.

Page. Harsh Reality. Dynamic Memory Allocation. Malloc Package. Process Memory Image. Assumptions. Malloc Example

Memory Allocation III

Dynamic Memory Alloca/on: Advanced Concepts

Memory Allocation III

Data sharing in OpenMP

2 Computing all Intersections of a Set of Segments Line Segment Intersection

Control-Flow Analysis and Loop Detection

CS201 Discussion 10 DRAWTREE + TRIES

Foundations of Computer Systems

Memory Allocation III

What are suffix trees?

Stack. A list whose end points are pointed by top and bottom

Data Flow on a Queue Machine. Bruno R. Preiss. Copyright (c) 1987 by Bruno R. Preiss, P.Eng. All rights reserved.

Orthogonal line segment intersection

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

Alignment of Long Sequences. BMI/CS Spring 2012 Colin Dewey

Midterm 2 Sample solution

ΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών

CS 221: Artificial Intelligence Fall 2011

From Dependencies to Evaluation Strategies

Memory Allocation III

Binghamton University Dynamic Memory Alloca/on

Fall 2018 Midterm 2 November 15, 2018

Unit 5 Vocabulary. A function is a special relationship where each input has a single output.

CS311H: Discrete Mathematics. Graph Theory IV. A Non-planar Graph. Regions of a Planar Graph. Euler s Formula. Instructor: Işıl Dillig

EECS 281: Homework #4 Due: Thursday, October 7, 2004

CSEP 573 Artificial Intelligence Winter 2016

Epson Projector Content Manager Operation Guide

Solving Problems by Searching. CS 486/686: Introduction to Artificial Intelligence Winter 2016

Real-Time Programming in Java

Fig.25: the Role of LEX

Dynamic Memory Allocation

Reducing a DFA to a Minimal DFA

Solving Problems by Searching. CS 486/686: Introduction to Artificial Intelligence

Algorithm Design (5) Text Search

Fall 2018 Midterm 1 October 11, ˆ You may not ask questions about the exam except for language clarifications.

COMBINATORIAL PATTERN MATCHING

UNIT 11. Query Optimization

Dynamic Memory Allocation: Advanced Concepts

LING/C SC/PSYC 438/538. Lecture 21 Sandiway Fong

Today. CS 188: Artificial Intelligence Fall Recap: Search. Example: Pancake Problem. Example: Pancake Problem. General Tree Search.

CS 432 Fall Mike Lam, Professor a (bc)* Regular Expressions and Finite Automata

MIPS I/O and Interrupt

Tries. Yufei Tao KAIST. April 9, Y. Tao, April 9, 2013 Tries

Unit #9 : Definite Integral Properties, Fundamental Theorem of Calculus

Lecture T4: Pattern Matching

Today. Search Problems. Uninformed Search Methods. Depth-First Search Breadth-First Search Uniform-Cost Search

pdfapilot Server 2 Manual

ΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών. Lecture 3b Lexical Analysis Elias Athanasopoulos

Lists in Lisp and Scheme

Presentation Martin Randers

Reducing Costs with Duck Typing. Structural

INTRODUCTION TO SIMPLICIAL COMPLEXES

Agenda & Reading. Class Exercise. COMPSCI 105 SS 2012 Principles of Computer Science. Arrays

Announcements. CS 188: Artificial Intelligence Fall Recap: Search. Today. Example: Pancake Problem. Example: Pancake Problem

1 Quad-Edge Construction Operators

COMP 423 lecture 11 Jan. 28, 2008

Regular Expression Matching with Multi-Strings and Intervals. Philip Bille Mikkel Thorup

Complete Coverage Path Planning of Mobile Robot Based on Dynamic Programming Algorithm Peng Zhou, Zhong-min Wang, Zhen-nan Li, Yang Li

Registering as an HPE Reseller

Symbol Table management

Homework. Context Free Languages III. Languages. Plan for today. Context Free Languages. CFLs and Regular Languages. Homework #5 (due 10/22)

CS481: Bioinformatics Algorithms

ITEC2620 Introduction to Data Structures

CS321 Languages and Compiler Design I. Winter 2012 Lecture 5

CMSC 331 First Midterm Exam

cisc1110 fall 2010 lecture VI.2 call by value function parameters another call by value example:

ECEN 468 Advanced Logic Design Lecture 36: RTL Optimization

Compression Outline :Algorithms in the Real World. Lempel-Ziv Algorithms. LZ77: Sliding Window Lempel-Ziv

Small Business Networking

Spring 2018 Midterm Exam 1 March 1, You may not use any books, notes, or electronic devices during this exam.

Small Business Networking

CSc 453. Compilers and Systems Software. 4 : Lexical Analysis II. Department of Computer Science University of Arizona

Paradigm 5. Data Structure. Suffix trees. What is a suffix tree? Suffix tree. Simple applications. Simple applications. Algorithms

Section 10.4 Hyperbolas

CSCI 104. Rafael Ferreira da Silva. Slides adapted from: Mark Redekopp and David Kempe

P(r)dr = probability of generating a random number in the interval dr near r. For this probability idea to make sense we must have

How to Design REST API? Written Date : March 23, 2015

Lexical Analysis. Amitabha Sanyal. ( as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

CSCI 446: Artificial Intelligence

Lexical analysis, scanners. Construction of a scanner

Transcription:

Keeping Trck o Free Blocks Method 1: : Implicit list using lengths -- links ll blocks Memory Alloction nd Usge Method : : Explicit list mong the ree blocks using pointers within the ree blocks CSE 361S Method 3: : Segregted ree lists Dierent ree lists or dierent size clsses Method 4: : Blocks sorted by size (not discussed) Cn use blnced tree (e.g. Red-Blck tree) with pointers within ech ree block, nd the length used s key Explicit Free Lists Allocting From Explicit Free Lists A B C pred succ Use dt spce or link pointers Typiclly doubly linked Still need boundry tgs or colescing Forwrd links A B 4 4 4 4 6 6 4 4 4 4 C Bck links Beore: Ater: (with splitting) ree block pred succ ree block It is importnt to relize tht links re not necessrily in the sme order s the blocks 3 4 Freeing With Explicit Free Lists Freeing With LIFO Policy Insertion policy: : Where in the ree list do you put newly reed block? LIFO (lst-in-irst-out) policy Insert reed block t the beginning o the ree list Pro: simple nd constnt time Con: studies suggest rgmenttion is worse thn ddress ordered. Address-ordered policy Insert reed blocks so tht ree list blocks re lwys in ddress order» i.e. ddr(pred) < ddr(curr) < ddr(succ) Con: requires serch Pro: studies suggest rgmenttion is better thn LIFO Cse 1: -- Insert sel t beginning o ree list Cse : -- Splice out next, colesce sel nd next, nd dd to beginning o ree list beore: ter: pred (p) sel sel succ (s) p s p s 5 6 Pge 1

Freeing With LIFO Policy (cont) Cse 3: -- 7 Splice out prev, colesce with sel, nd dd to beginning o ree list Cse 4: -- Splice out prev nd next, colesce with sel, nd dd to beginning o list beore: ter: beore: ter: p p p1 s s s1 sel sel p s p1 s1 p s Explicit List Summry Comprison to implicit list: Allocte is liner time in number o ree blocks insted o totl blocks -- much ster lloctes when most o the memory is ull Slightly more complicted llocte nd ree since needs to splice blocks in nd out o the list Some extr spce or the links ( extr words needed or ech block) Min use o linked lists is in conjunction with segregted ree lists 8 Keep multiple linked lists o dierent size clsses, or possibly or dierent types o objects Keeping Trck o Free Blocks Method 1: Implicit list using lengths -- links ll blocks Method : Explicit list mong the ree blocks using pointers within the ree blocks Method 3: Segregted ree list Dierent ree lists or dierent size clsses Method 4: : Blocks sorted by size 9 Cn use blnced tree (e.g. Red-Blck tree) with pointers within ech ree block, nd the length used s key Segregted Storge Ech size clss hs its own collection o blocks 10 1-3 4 5-8 9-16 Oten hve seprte size clss or every smll size (,3,4, ) For lrger sizes typiclly hve size clss or ech power o Simple Segregted Storge Seprte hep nd ree list or ech size clss No splitting To llocte block o size n: I ree list or size n is not empty, llocte irst block on list (note, list cn be implicit or explicit) I ree list is empty, get new pge crete new ree list rom ll blocks in pge llocte irst block on list Constnt time To ree block: Add to ree list I pge is empty, return the pge or use by nother size (optionl) Trdeos: Fst, but cn rgment bdly 11 Segregted Fits Arry o ree lists, ech one or some size clss To llocte block o size n: Serch pproprite ree list or block o size m > n I n pproprite block is ound: Split block nd plce rgment on pproprite list (optionl) I no block is ound, try next lrger clss Repet until block is ound To ree block: Colesce nd plce on pproprite list (optionl) Trdeos Fster serch thn sequentil its (i.e., log time or power o two size clsses) Controls rgmenttion o simple segregted storge Colescing cn increse serch times Deerred colescing cn help 1 Pge

For More Ino on Alloctors D. Knuth, The Art o Computer Progrmming, Second Edition, Addison Wesley, 1973 The clssic reerence on dynmic storge lloction Wilson et l, Dynmic Storge Alloction: A Survey nd Criticl Review, Proc. 1995 Int l Workshop on Memory Mngement, Kinross, Scotlnd, Sept, 1995. Comprehensive survey Avilble rom CS:APP student site (cspp.cs.cmu.edu) 13 Implicit Memory Mngement: Grbge Collection Grbge collection: utomtic reclmtion o hep- llocted storge -- ppliction never hs to ree void oo() { int *p = mlloc(18); return; /* p block is now grbge */ Common in unctionl lnguges, scripting lnguges, nd modern object oriented lnguges: Lisp, ML, Jv, Perl, Mthemtic, Vrints (conservtive grbge collectors) exist or C nd C++ Cnnot collect ll grbge 14 Grbge Collection How does the memory mnger know when memory cn be reed? In generl we cnnot know wht is going to be used in the uture since it depends on conditionls But we cn tell tht certin blocks cnnot be used i there re no pointers to them Need to mke certin ssumptions bout pointers Memory mnger cn distinguish pointers rom nonpointers All pointers point to the strt o block Cnnot hide pointers (e.g., by coercing them to n int, nd then bck gin) Clssicl GC lgorithms Mrk nd sweep collection (McCrthy, 1960) Does not move blocks (unless you lso compct ) Reerence counting (Collins, 1960) Does not move blocks (not discussed) Copying collection (Minsky, 1963) Moves blocks (not discussed) For more inormtion, see Jones nd Lin, Grbge Collection: Algorithms or Automtic Dynmic Memory, John Wiley & Sons, 1996. 15 16 Memory s Grph We view memory s directed grph Ech block is node in the grph Ech pointer is n edge in the grph Loctions not in the hep tht contin pointers into the hep re clled root nodes (e.g. registers, loctions on the stck, globl vribles) Root nodes Hep nodes rechble Not-rechble (grbge) A node (block) is rechble i there is pth rom ny root to tht node. Non-rechble nodes re grbge (never needed by the ppliction) 17 Assumptions For This Lecture Appliction new(n): returns pointer to new block with ll loctions clered red(b,i): red loction i o block b into register write(b,i,v): write v into loction i o block b Ech block will hve heder word ddressed s b[-1], or block b 18 Used or dierent purposes in dierent collectors Instructions used by the Grbge Collector is_ptr(p): determines whether p is pointer length(b): returns the length o block b, not including the heder get_roots(): returns ll the roots Pge 3

Mrk nd Sweep Collecting Cn build on top o mlloc/ree pckge Allocte using mlloc until you run out o spce When out o spce: 19 Use extr mrk bit in the hed o ech block Mrk: Strt t roots nd set mrk bit on ll rechble memory Sweep: Scn ll blocks nd ree blocks tht re not mrked Beore mrk Ater mrk Ater sweep ree root ree Mrk bit set Mrk nd Sweep (cont.) 0 Mrk using depth-irst trversl o the memory grph ptr mrk(ptr p) { i (!is_ptr(p)) return; // do nothing i not pointer i (mrkbitset(p)) return // check i lredy mrked setmrkbit(p); // set the mrk bit or (i=0; i < length(p); i++) // mrk ll children mrk(p[i]); return; Sweep using lengths to ind next block ptr sweep(ptr p, ptr end) { while (p < end) { i mrkbitset(p) clermrkbit(); else i (lloctebitset(p)) ree(p); p += length(p); Memory-Relted Bugs Dereerencing bd pointers Reding uninitilized memory Overwriting memory Reerencing nonexistent vribles Freeing blocks multiple times Reerencing reed blocks Filing to ree blocks Dereerencing Bd Pointers The clssic scn bug scn( %d, vl); 1 Reding Uninitilized Memory Assuming tht hep dt is initilized to zero Allocting the (possibly) wrong sized object /* return y = Ax */ int *mtvec(int **A, int *x) { int *y = mlloc(n*sizeo(int)); int i, j; or (i=0; i<n; i++) or (j=0; j<n; j++) y[i] += A[i][j]*x[j]; return y; int **p; p = mlloc(n*sizeo(int)); or (i=0; i<n; i++) { p[i] = mlloc(m*sizeo(int)); 3 4 Pge 4

O-by-one error Not checking the mx string size int **p; p = mlloc(n*sizeo(int *)); or (i=0; i<=n; i++) { p[i] = mlloc(m*sizeo(int)); chr s[8]; int i; gets(s); /* reds 13456789 rom stdin */ Bsis or clssic buer overlow ttcks 1988 Internet worm Modern ttcks on Web servers AOL/Microsot IM wr 5 6 Reerencing pointer insted o the object it points to Misunderstnding pointer rithmetic int *BinhepDelete(int **binhep, int *size) { int *pcket; pcket = binhep[0]; binhep[0] = binhep[*size - 1]; *size--; Hepiy(binhep, *size, 0); return(pcket); int *serch(int *p, int vl) { while (*p && *p!= vl) p += sizeo(int); return p; 7 8 Reerencing Nonexistent Vribles Freeing Blocks Multiple Times Forgetting tht locl vribles dispper when unction returns int *oo () { int vl; return &vl; Nsty! x = mlloc(n*sizeo(int)); <mnipulte x> ree(x); y = mlloc(m*sizeo(int)); <mnipulte y> ree(x); 9 30 Pge 5

Reerencing Freed Blocks Evil! Filing to Free Blocks (Memory Leks) Slow, long-term killer! x = mlloc(n*sizeo(int)); <mnipulte x> ree(x);... y = mlloc(m*sizeo(int)); or (i=0; i<m; i++) y[i] = x[i]++; oo() { int *x = mlloc(n*sizeo(int));... return; 31 3 Filing to Free Blocks (Memory Leks) Freeing only prt o dt structure struct list { int vl; struct list *next; ; oo() { struct list *hed = mlloc(sizeo(struct list)); hed->vl = 0; hed->next = NULL; <crete nd mnipulte the rest o the list>... ree(hed); return; 33 Pge 6