Review! Lecture 5 C Memory Management !

Similar documents
CS61C : Machine Structures

CS61C : Machine Structures

CS61C : Machine Structures

Lectures 13 & 14. memory management

CS61C : Machine Structures

CS61C : Machine Structures

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

CS61C : Machine Structures

CS61C : Machine Structures

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

Lecture 7: Procedures and Program Execution Preview

CS61C Midterm Review on C & Memory Management

ECE 15B COMPUTER ORGANIZATION

Lecture 10: Program Development versus Execution Environment

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

Dynamic Memory Allocation

Arrays and Memory Management

Another View of the Memory Hierarchy. Lecture #25 Virtual Memory I Memory Hierarchy Requirements. Memory Hierarchy Requirements

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

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

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

Operating System Labs. Yuanbin Wu

CS61C : Machine Structures

CS 61C: Great Ideas in Computer Architecture. Memory Management and Usage

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

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

Review. You Are Here! Recap: The Stack 11/8/12. CS 61C: Great Ideas in Computer Architecture C Memory Management. Recap: C Memory Management

UC Berkeley CS61C : Machine Structures

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

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III

Memory management. Johan Montelius KTH

Optimizing Dynamic Memory Management

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

Dynamic Memory Allocation

ECE 598 Advanced Operating Systems Lecture 10

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

CS61C : Machine Structures

How about them A s!! Go Oaktown!! CS61C - Machine Structures. Lecture 4 C Structures Memory Management Dan Garcia.

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Dynamic Memory Management! Goals of this Lecture!

Brought to you by CalLUG (UC Berkeley GNU/Linux User Group). Tuesday, September 20, 6-8 PM in 100 GPB.

Lecture #6 Intro MIPS; Load & Store Assembly Variables: Registers (1/4) Review. Unlike HLL like C or Java, assembly cannot use variables

Numbers: positional notation. CS61C Machine Structures. Faux Midterm Review Jaein Jeong Cheng Tien Ee. www-inst.eecs.berkeley.

CSC 1600 Memory Layout for Unix Processes"

Dynamic Memory Management

CS61C : Machine Structures

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

And in Review! ! Locality of reference is a Big Idea! 3. Load Word from 0x !

Inequalities in MIPS (2/4) Inequalities in MIPS (1/4) Inequalities in MIPS (4/4) Inequalities in MIPS (3/4) UCB CS61C : Machine Structures

Dynamic Memory Management

Class Information ANNOUCEMENTS

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

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

Recitation #11 Malloc Lab. November 7th, 2017

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

Introduction to Computer Architecture

Programming Languages

ANITA S SUPER AWESOME RECITATION SLIDES

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

Dynamic Memory Allocation: Basic Concepts

ECE 598 Advanced Operating Systems Lecture 12

Run-time Environments - 3

The Art and Science of Memory Allocation

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

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

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

More C Pointer Dangers

Dynamic Memory Allocation I

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

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

Engine Support System. asyrani.com

10.1. CS356 Unit 10. Memory Allocation & Heap Management

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Dynamic Memory Allocation: Basic Concepts

Classifying Information Stored in Memory! Memory Management in a Uniprogrammed System! Segments of a Process! Processing a User Program!

Dynamic Memory: Alignment and Fragmentation

Memory Hierarchy Requirements. Three Advantages of Virtual Memory

Heap Arrays. Steven R. Bagley

CS61C : Machine Structures

Agenda. Recap: C Memory Management. Agenda. Recap: Where are Variables Allocated? Recap: The Stack 11/15/10

Lecture #6 Intro MIPS; Load & Store

Memory Allocation II. CSE 351 Autumn Instructor: Justin Hsia

Programs in memory. The layout of memory is roughly:

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

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

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

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

Dynamic Memory Allocation I Nov 5, 2002

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

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

Pointers, Arrays, Memory: AKA the cause of those Segfaults

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Advanced Programming & C++ Language

Dynamic Memory Allocation. Zhaoguo Wang

CS24 Week 2 Lecture 1

CSC369 Lecture 5. Larry Zhang, October 19,2015

Transcription:

CS61C L05 C Memory Management (1)! inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management 2010-06-28!!! Instructor Paul Pearce! Symmetric multiprocessor! MIPS support for Android MIPS Technologies (founded by John Hennessy, author of your textbook!) recently announced support for SMP on Android. This week, youʼll learn MIPS! http://tinyurl.com/297ne2j Review! Use handles to change pointers! Create abstractions (and your own data structures) with structures! Dynamically allocated heap memory must be manually deallocated in C.! Use malloc() and free() to allocate and de-allocate persistent storage.! CS61C L05 C Memory Management (2)! How big are structs?! Recall C operator sizeof() which gives size in bytes (of type or variable)! How big is sizeof(p)?! struct p { char x; int y; ;! 5 bytes? 8 bytes?! Compiler may word align integer y Takeaway: Structs can be padded, use sizeof()! Donʼt forget the globals!! Remember:! Structure declaration does not allocate memory! Variable declaration does allocate memory! So far we have talked about several different ways to allocate memory for data:! 1. Declaration of a local variable! int i; struct Node list; char *string; int ar[n];! 3. Dynamic allocation at runtime by calling allocation function (malloc).! ptr = (struct Node *) malloc(sizeof(struct Node)*n);! One more possibility exists! int myglobal; 3. Data declared outside of any procedure (i.e., before main).! main() { Similar to #1 above, but has global scope.! CS61C L05 C Memory Management (3)! CS61C L05 C Memory Management (4)! C Memory Management! C has 3 pools of memory! Static storage: global variable storage, basically permanent, entire program run! The Stack: local variable storage, parameters, return address (location of activation records in Java or stack frame in C)! The Heap (dynamic malloc storage): data lives until deallocated by programmer! C requires knowing where objects are in memory, otherwise things donʼt work as expected! Java hides location of objects! CS61C L05 C Memory Management (5)! Normal C Memory Management! A programʼs address space contains 4 regions:! stack: local variables, grows downward! heap: space requested for pointers via malloc() ; resizes dynamically, grows upward! static data: variables declared outside main, does not grow or shrink! code: loaded when program starts, does not change! CS61C L05 C Memory Management (6)! ~ FFFF FFFF hex " ~ 0 hex " stack" heap" static data" code" For now, OS somehow prevents accesses between stack and heap (gray hash lines). Wait for virtual memory"

CS61C L05 C Memory Management (7)! Where are variables allocated?! If declared outside a procedure, allocated in static storage! If declared inside procedure, allocated on the stack and freed when procedure returns.! main() is a procedure! int myglobal; main() { int mytemp; The Stack! Stack frame includes:! Return instruction address! Parameters! Space for other local variables! Stack frames contiguous blocks of memory; stack pointer tells where bottom stack frame is! When procedure ends, stack frame is tossed off the stack; frees memory for future stack frames! CS61C L05 C Memory Management (8)! Stack! Last In, First Out (LIFO) data structure! main () { a(0); void a (int m) { b(1); void b (int n) { c(2); void c (int o) { d(3); void d (int p) { Stack grows down" stack" Who cares about stack management?! Pointers in C allow access to deallocated memory, leading to hard-to-find bugs!! int *fun() { int y; y = 3; return &y; ; main () { main" fun() (y==3)" main" main" printf() (y==?)" int *stackaddr,content; stackaddr = fun(); content = *stackaddr; printf("%d", content); /* 3 */ content = *stackaddr; printf("%d", content); /*13451514 */ ; CS61C L05 C Memory Management (9)! CS61C L05 C Memory Management (10)! The Heap (Dynamic memory)! Large pool of memory, not allocated in contiguous order! back-to-back requests for heap memory could result blocks very far apart! where Java new command allocates memory! In C, specify number of bytes of memory explicitly to allocate item! int *ptr; ptr = (int *) malloc(sizeof(int)); /* malloc returns type (void *), so need to cast to right type */ malloc(): Allocates raw, uninitialized memory from heap! Memory Management! How do we manage memory?! Code, Static storage are easy: they never grow or shrink! Stack space is also easy: stack frames are created and destroyed in last-in, first-out (LIFO) order! Managing the heap is tricky: memory can be allocated / deallocated at any time! CS61C L05 C Memory Management (11)! CS61C L05 C Memory Management (12)!

CS61C L05 C Memory Management (13)! Heap Management Requirements! Want malloc() and free() to run quickly.! Want minimal memory overhead! Want to avoid fragmentation* when most of our free memory is in many small chunks" In this case, we might have many free bytes but not be able to satisfy a large request since the free bytes are not contiguous in memory.! * This is technically called external fragmention" Heap Management! An example! Request R1 for 100 Request R2 for 1 byte! Memory from R1 is freed! Request R3 for 50 What if R3 was a request for 101 bytes?! R2 (1 byte)" R1 (100 bytes)" CS61C L05 C Memory Management (14)! Heap Management! Administrivia! An example! Request R1 for 100 Request R2 for 1 byte! Memory from R1 is freed! Request R3 for 50 What if R3 was a request for 101 bytes?! R2 (1 byte)" R3?" R3?" You made it through the first week! Yay!! Donʼt forget about the newsgroup!! Hasnʼt been used as much as Paul would like. Paul has elaborated on some things from lecture on the newsgroup!! We start assembly tomorrow. Donʼt forget about the reading! HW 2 due tomorrow at midnight.! Project 1 out now. Start early, lots of code to understand (and itʼs really fun!)! Check back of handout for CS Illustrated on pointers and arrays!! CS61C L05 C Memory Management (15)! CS61C L05 C Memory Management (16)! More Administrivia!! Tentative schedule for the rest of the summer now online!! Plan accordingly!! Midterm currently slated for Thursday July 15 th from 6pm-9pm! Does anyone have a hard conflict with this time?! Final time will be determined based on how the midterm goes at the scheduled time. The final will be on Thursday, August 12 th! Pick up a copy of the cheating policy from the front. On it please write your name, login, and then sign it. Youʼll need to give this to your Lab TA in order to be checked off for Lab 3!! K&R Malloc/Free Implementation! From Section 8.7 of K&R! Code in the book uses some C language features we havenʼt discussed and is written in a very terse style, donʼt worry if you canʼt decipher the code! Each block of memory is preceded by a header that has two fields: size of the block and a pointer to the next block! All free blocks are kept in a circular linked list, the pointer field is unused in an allocated block! CS61C L05 C Memory Management (17)! CS61C L05 C Memory Management (18)!

CS61C L05 C Memory Management (19)! K&R Implementation! malloc() searches the free list for a block that is big enough. If none is found, more memory is requested from the operating system. If what it gets canʼt satisfy the request, it fails.! free() checks if the blocks adjacent to the freed block are also free! If so, adjacent free blocks are merged (coalesced) into a single, larger free block! Otherwise, the freed block is just added to the free list! Choosing a block in malloc() If there are multiple free blocks of memory that are big enough for some request, how do we choose which one to use?! best-fit: choose the smallest block that is big enough for the request! first-fit: choose the first block we see that is big enough! next-fit: like first-fit but remember where we finished searching and resume searching from there! CS61C L05 C Memory Management (20)! Slab Allocator! Slab Allocator! A different approach to memory management (used in GNU libc)! Divide blocks in to large and small by picking an arbitrary threshold size. Blocks larger than this threshold are managed with a freelist (as before).! For small blocks, allocate blocks in sizes that are powers of 2! e.g., if program wants to allocate 20 bytes, actually give it 32 Bookkeeping for small blocks is relatively easy: just use a bitmap for each range of blocks of the same size! Allocating is easy and fast: compute the size of the block to allocate and find a free bit in the corresponding bitmap.! Freeing is also easy and fast: figure out which slab the address belongs to and clear the corresponding bit.! CS61C L05 C Memory Management (21)! CS61C L05 C Memory Management (22)! Slab Allocator! Slab Allocator Tradeoffs! 16 byte blocks:" 32 byte blocks:" 64 byte blocks:" 16 byte block bitmap: 11011000" 32 byte block bitmap: 0111" 64 byte block bitmap: 00" Extremely fast for small blocks.! Slower for large blocks! But presumably the program will take more time to do something with a large block so the overhead is not as critical.! Minimal space overhead! No fragmentation (as we defined it before) for small blocks, but still have wasted space!! CS61C L05 C Memory Management (23)! CS61C L05 C Memory Management (24)!

CS61C L05 C Memory Management (25)! Internal vs. External Fragmentation! With the slab allocator, difference between requested size and next power of 2 is wasted! e.g., if program wants to allocate 20 bytes and we give it a 32 byte block, 12 bytes are unused.! We also refer to this as fragmentation, but call it internal fragmentation since the wasted space is actually within an allocated block.! External fragmentation: wasted space between allocated blocks.! Buddy System! Yet another memory management technique (used in Linux kernel)! Like GNUʼs slab allocator, but only allocate blocks in sizes that are powers of 2 (internal fragmentation is possible)! Keep separate free lists for each size! e.g., separate free lists for 16 byte, 32 byte, 64 byte blocks, etc.! CS61C L05 C Memory Management (26)! Buddy System! If no free block of size n is available, find a block of size 2n and split it in to two blocks of size n! When a block of size n is freed, if its neighbor of size n is also free, combine the blocks in to a single block of size 2n! Buddy is block in other half larger block buddies" NOT buddies" Same speed advantages as slab allocator! Allocation Schemes! So which memory management scheme (K&R, slab, buddy) is best?! There is no single best approach for every application.! Different applications have different allocation / deallocation patterns.! A scheme that works well for one application may work poorly for another application.! CS61C L05 C Memory Management (27)! CS61C L05 C Memory Management (28)! Peer Instruction Pros and Cons of fits! 1) first-fit results in many small blocks at the beginning of the free list! 2) next-fit is slower than first-fit, since it takes longer in steady state to find a match! 3) best-fit leaves lots of tiny blocks! 123 a) FFT b) FTT c) TFF d) TFT e) TTT And in conclusion! C has 3 pools of memory! Static storage: global variable storage, basically permanent, entire program run! The Stack: local variable storage, parameters, return address! The Heap (dynamic storage): malloc() grabs space from here, free() returns it.! malloc() handles free space with freelist. Three different ways to find free space when given a request:! First fit (find first one thatʼs free)! Next fit (same as first, but remembers where left off)! Best fit (finds most snug free space)! Internal vs External fragmentation!! CS61C L05 C Memory Management (29)! CS61C L05 C Memory Management (31)!

CS61C L05 C Memory Management (32)! Bonus slides! These are extra slides that used to be included in lecture notes, but have been moved to this, the bonus area to serve as a supplement.! The slides will appear in the order they would have in the normal presentation! Intel 80x86 C Memory Management! A C programʼs 80x86 address space :! heap: space requested for pointers via malloc(); resizes dynamically, grows upward! static data: variables declared outside main, does not grow or shrink! code: loaded when program starts, does not change! stack: local variables, grows downward! CS61C L05 C Memory Management (33)! ~ 08000000 hex " heap" static data" code" stack" Tradeoffs of allocation policies! Best-fit: Tries to limit fragmentation but at the cost of time (must examine all free blocks for each malloc). Leaves lots of small blocks (why?)! First-fit: Quicker than best-fit (why?) but potentially more fragmentation. Tends to concentrate small blocks at the beginning of the free list (why?)! Next-fit: Does not concentrate small blocks at front like first-fit, should be faster as a result.! CS61C L05 C Memory Management (34)!