CS61C : Machine Structures

Similar documents
CS61C : Machine Structures

Review! Lecture 5 C Memory Management !

Lectures 13 & 14. memory management

CS61C : Machine Structures

CS61C : Machine Structures

CS61C : Machine Structures

ECE 15B COMPUTER ORGANIZATION

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

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

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

CS61C : Machine Structures

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

CS61C : Machine Structures

CS61C : Machine Structures

Lecture 7: Procedures and Program Execution Preview

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

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

Lecture 10: Program Development versus Execution Environment

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

Arrays and Memory Management

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

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

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

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

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

CS61C : Machine Structures

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

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

CS61C : Machine Structures

CS61C : Machine Structures

CS61C Midterm Review on C & Memory Management

Lecture #6 Intro MIPS; Load & Store

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

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

CS24 Week 2 Lecture 1

Agenda. Pointer Arithmetic. Pointer Arithmetic pointer + number, pointer number 6/23/2011. Pointer Arithmetic: Peer Instruction Question

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

CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models

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

Introduction to Computer Architecture

Functions:"" Breaking"large"computing"tasks"to" smaller"ones"

UC Berkeley CS61C : Machine Structures

Dynamic Memory Management

Dynamic Memory Management! Goals of this Lecture!

CS 110 Computer Architecture. Lecture 4: Introduction to C, Part III. Instructor: Sören Schwertfeger.

CS 11 C track: lecture 5

CSC 1600 Memory Layout for Unix Processes"

Programs in memory. The layout of memory is roughly:

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

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

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

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

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

Dynamic Memory Allocation

Class Information ANNOUCEMENTS

CS61C : Machine Structures

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

Dynamic Memory Management

Memory management. Johan Montelius KTH

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Heap Arrays. Steven R. Bagley

HW1 due Monday by 9:30am Assignment online, submission details to come

Heap Arrays and Linked Lists. Steven R. Bagley

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Memory Allocation. General Questions

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

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

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

Dynamic Data Structures. CSCI 112: Programming in C

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Run-time Environments - 3

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

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

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

CS 61c: Great Ideas in Computer Architecture

More C Pointer Dangers

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

C Programming Basics II

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Lecture 8 Dynamic Memory Allocation

CS61C : Machine Structures

CS61, Fall 2012 Section 2 Notes

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

CS61C : Machine Structures

Low-Level C Programming. Memory map Pointers Arrays Structures

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Dynamic Memory Allocation and Linked Lists

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

Operating System Labs. Yuanbin Wu

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

CS 2113 Software Engineering

Dynamic Memory Allocation: Basic Concepts

Intermediate Programming, Spring 2017*

Transcription:

inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Memory Management 2007-06-28 Scott Beamer, Instructor iphone Comes out Tomorrow CS61C L4 C Memory Management (1) www.apple.com/iphone

Review C99 is the update to the ANSI standard Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, w/little protection Array bounds not checked Variables not automatically initialized (Beware) The cost of efficiency is more overhead for the programmer. C gives you a lot of extra rope but be careful not to hang yourself with it! Use handles to change pointers P. 53 is a precedence table, useful for (e.g.,) x = ++*p; *p = *p + 1 ; x = *p; CS61C L4 C Memory Management (2)

Binky Pointer Video (thanks to NP @ SU) CS61C L4 C Memory Management (3)

C structures : Overview A struct is a data structure composed for simpler data types. Like a class in Java/C++ but without methods or inheritance. struct point { int x; int y; }; void PrintPoint(struct point p) { printf( (%d,%d), p.x, p.y); } CS61C L4 C Memory Management (4)

C structures: Pointers to them The C arrow operator (->) dereferences and extracts a structure field with a single operator. The following are equivalent: struct point *p; printf( x is %d\n, (*p).x); printf( x is %d\n, p->x); CS61C L4 C Memory Management (5)

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 CS61C L4 C Memory Management (6)

Linked List Example Let s look at an example of using structures, pointers, malloc(), and free() to implement a linked list of strings. struct Node { char *value; struct Node *next; }; typedef struct Node *List; /* Create a new (empty) list */ List ListNew(void) { return NULL; } CS61C L4 C Memory Management (7)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } list: node:? NULL string: abc CS61C L4 C Memory Management (8)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } list: node:? NULL string:? abc CS61C L4 C Memory Management (9)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } list: node:????? string: abc NULL CS61C L4 C Memory Management (10)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } list: node:? abc string: abc NULL CS61C L4 C Memory Management (11)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } list: node: abc string: abc NULL CS61C L4 C Memory Management (12)

Linked List Example /* add a string to an existing list */ List list_add(list list, char *string) { struct Node *node = (struct Node*) malloc(sizeof(struct Node)); node->value = (char*) malloc(strlen(string) + 1); strcpy(node->value, string); node->next = list; return node; } node: NULL abc CS61C L4 C Memory Management (13)

And in Semi-Conclusion Use handles to change pointers Create abstractions with structures Dynamically allocated heap memory must be manually deallocated in C. Use malloc() and free() to allocate and deallocate memory from heap. CS61C L4 C Memory Management (14)

Peer Instruction Which are guaranteed to print out 5? I: main() { int *a-ptr; *a-ptr = 5; printf( %d, *a-ptr); } II: main() { int *p, a = 5; p = &a;... /* code; a & p NEVER on LHS of = */ printf( %d, a); } III: main() { int *ptr; ptr = (int *) malloc (sizeof(int)); *ptr = 5; printf( %d, *ptr); } CS61C L4 C Memory Management (15) I II III 1: - - - 2: - - YES 3: - YES - 4: - YES YES 5: YES - - 6: YES - YES 7: YES YES - 8: YES YES YES

Peer Instruction int main(void){ int A[] = {5,10}; int *p = A; 5 10 A[1] A[0] printf( %u %d %d %d\n,p,*p,a[0],a[1]); p = p + 1; printf( %u %d %d %d\n,p,*p,a[0],a[1]); *p = *p + 1; printf( %u %d %d %d\n,p,*p,a[0],a[1]); } If the first printf outputs 100 5 5 10, what will the other two printf output? 1: 101 10 5 10 then 101 11 5 11 2: 104 10 5 10 then 104 11 5 11 3: 101 <other> 5 10 then 101 <3-others> 4: 104 <other> 5 10 then 104 <3-others> 5: One of the two printfs causes an ERROR 6: I surrender! p CS61C L4 C Memory Management (16)

Administrivia Assignments HW1 due 7/1 @ 11:59pm HW2 due 7/4 @ 11:59pm No class on 7/4 Another section is in the works It won t be official until the last minute Keep checking the course website Once known I will email people on waitlist CS61C L4 C Memory Management (17)

Where is data allocated? Structure declaration does not allocate memory Variable declaration does allocate memory If declare outside a procedure, allocated in static storage If declare inside procedure, allocated on the stack and freed when procedure returns. - NB: main() is a procedure int myglobal; main() { int mytemp; } CS61C L4 C Memory Management (18)

The Stack Stack frame includes: Return address Parameters Space for other local variables Stack frames contiguous blocks of memory; stack pointer tells where top stack frame is When procedure ends, stack frame is tossed off the stack; frees memory for future stack frames SP frame frame frame frame CS61C L4 C Memory Management (19)

Stack Last In, First Out (LIFO) memory usage 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 Pointer Stack Pointer Stack Pointer Stack Pointer Stack Pointer stack CS61C L4 C Memory Management (20)

Who cares about stack management? Pointers in C allow access to deallocated memory, leading to hard-to-find bugs! int * ptr () { int y; y = 3; return &y; }; main () { main ptr() (y==3) SP main main printf() (y==?) SP SP int *stackaddr,content; stackaddr = ptr(); content = *stackaddr; printf("%d", content); /* 3 */ content = *stackaddr; printf("%d", content); /*13451514 */ }; CS61C L4 C Memory Management (21)

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 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 L4 C Memory Management (22)

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 CS61C L4 C Memory Management (23)

Review: 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 L4 C Memory Management (24) ~ 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

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 ~ 08000000 hex heap static data code stack CS61C L4 C Memory Management (25)

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 L4 C Memory Management (26)

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. CS61C L4 C Memory Management (27)

Heap Management An example Request R1 for 100 bytes Request R2 for 1 byte Memory from R1 is freed Request R3 for 50 bytes R2 (1 byte) R1 (100 bytes) CS61C L4 C Memory Management (28)

Heap Management An example Request R1 for 100 bytes Request R2 for 1 byte Memory from R1 is freed Request R3 for 50 bytes R2 (1 byte) R3? R3? CS61C L4 C Memory Management (29)

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 linked list, the pointer field is unused in an allocated block CS61C L4 C Memory Management (30)

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 CS61C L4 C Memory Management (31)

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 L4 C Memory Management (32)

Peer Instruction Pros and Cons of fits A. The con of first-fit is that it results in many small blocks at the beginning of the free list B. The con of next-fit is it is slower than first-fit, since it takes longer in steady state to find a match C. The con of best-fit is that it leaves lots of tiny blocks CS61C L4 C Memory Management (33) ABC 1: FFF 2: FFT 3: FTF 4: FTT 5: TFF 6: TFT 7: TTF 8: TTT

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 L4 C Memory Management (34)

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) CS61C L4 C Memory Management (35)