CS61C : Machine Structures

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

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

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

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?!

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

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

Has there been an update to ANSI C? Lecture #3 C Pointers Yes! It s called the C99 or C9x std

CS61C : Machine Structures

CS61C : Machine Structures

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

Lectures 13 & 14. memory management

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

CS61C : Machine Structures

CS61C : Machine Structures

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

ECE 15B COMPUTER ORGANIZATION

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

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

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

CS61C : Machine Structures

More C Pointer Dangers

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

Introduction to Computer Architecture

CS61C : Machine Structures

CS 61c: Great Ideas in Computer Architecture

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

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

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

C Arrays, Strings, More Pointers Instructor: Steven Ho

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

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

Intermediate Programming, Spring 2017*

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

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

IT 252 Computer Organization and Architecture Introduction to the C Programming Language

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Intro to C: Pointers and Arrays

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

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

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

Lecture 2: C Programm

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS24 Week 2 Lecture 1

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Arrays and Memory Management

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

Heap Arrays and Linked Lists. Steven R. Bagley

CS 11 C track: lecture 5

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

Review! Lecture 5 C Memory Management !

CS61C : Machine Structures

Dynamic Data Structures. CSCI 112: Programming in C

Lecture 7 More Memory Management Slab Allocator. Slab Allocator

Pointers in C/C++ 1 Memory Addresses 2

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CSC C69: OPERATING SYSTEMS

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Instructor: Randy H. Katz hbp://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #4. Agenda

CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II

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

Character Strings. String-copy Example

CMSC 341 Lecture 2 Dynamic Memory and Pointers

ME964 High Performance Computing for Engineering Applications

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

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

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

CSC 1600 Memory Layout for Unix Processes"

Lecture 7: Procedures and Program Execution Preview

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

CS61C : Machine Structures

CS61C : Machine Structures

Homework #3 CS2255 Fall 2012

CS61C : Machine Structures

C'Programming' data'separate'from'methods/functions' Low'memory'overhead'compared'to'Java'

Number review... Lecture 3 Introduction to the C Programming Language (pt 1) Has there been an update to ANSI C?

CS61C : Machine Structures

CS61, Fall 2012 Section 2 Notes

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Lectures 5-6: Introduction to C

Introduction to C: Pointers

Heap Arrays. Steven R. Bagley

REFERENCES, POINTERS AND STRUCTS

Arrays and Pointers in C. Alan L. Cox

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

C Programming Basics II

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

Agenda. Address vs. Value Consider memory to be a single huge array. Review. Pointer Syntax. Pointers 9/9/12

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Arrays and Pointers (part 1)

CS61C : Machine Structures

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Programming in C - Part 2

Transcription:

inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 Introduction to C (pt 3) C Memory Management CS61C L05 Introduction to C (pt 3) (1) 2007-01-26 Lecturer SOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Norway: itunes illegal! Norway ruled that itunes was illegal because it did not allow downloaded songs encoded with their proprietary Fairplay system to be played on non-ipods. They are asking Apple to open their system up by Oct 1. www.msnbc.msn.com/id/16793043/ There is one handout today at the front and back of the room!

Review Pointers and arrays are virtually same C knows how to increment pointers C is an efficient language, with 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! CS61C L05 Introduction to C (pt 3) (2)

C Strings A string in C is just an array of characters. char string[] = "abc"; How do you tell how long a string is? Last character is followed by a 0 byte (null terminator) int strlen(char s[]) { int n = 0; while (s[n]!= 0) n++; return n; } CS61C L05 Introduction to C (pt 3) (3)

Pointers (1/4) review Sometimes you want to have a procedure increment a variable? What gets printed? void AddOne(int x) { x = x + 1; } y = 5 int y = 5; AddOne( y); printf( y = %d\n, y); CS61C L05 Introduction to C (pt 3) (4)

Pointers (2/4) review Solved by passing in a pointer to our subroutine. Now what gets printed? void AddOne(int *p) { *p = *p + 1; } y = 6 int y = 5; AddOne(&y); printf( y = %d\n, y); CS61C L05 Introduction to C (pt 3) (5)

Pointers (3/4) But what if what you want changed is a pointer? What gets printed? void IncrementPtr(int *p) { p = p + 1; } A q *q = 50 int A[3] = {50, 60, 70}; int *q = A; IncrementPtr( q); printf( *q = %d\n, *q); 50 60 70 CS61C L05 Introduction to C (pt 3) (6)

Pointers (4/4) Solution! Pass a pointer to a pointer, declared as **h Now what gets printed? void IncrementPtr(int **h) { *h = *h + 1; } A q *q = 60 q int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); printf( *q = %d\n, *q); 50 60 70 CS61C L05 Introduction to C (pt 3) (7)

Dynamic Memory Allocation (1/4) C has operator sizeof() which gives size in bytes (of type or variable) Assume size of objects can be misleading and is bad style, so use sizeof(type) Many years ago an int was 16 bits, and programs were written with this assumption. What is the size of integers now? sizeof knows the size of arrays: int ar[3]; // Or: int ar[] = {54, 47, 99} sizeof(ar) 12 as well for arrays whose size is determined at run-time: int n = 3; int ar[n]; // Or: int ar[fun_that_returns_3()]; sizeof(ar) 12 CS61C L05 Introduction to C (pt 3) (8)

Dynamic Memory Allocation (2/4) To allocate room for something new to point to, use malloc() (with the help of a typecast and sizeof): ptr = (int *) malloc (sizeof(int)); Now, ptr points to a space somewhere in memory of size (sizeof(int)) in bytes. (int *) simply tells the compiler what will go into that space (called a typecast). malloc is almost never used for 1 var ptr = (int *) malloc (n*sizeof(int)); This allocates an array of n integers. CS61C L05 Introduction to C (pt 3) (9)

Dynamic Memory Allocation (3/4) Once malloc() is called, the memory location contains garbage, so don t use it until you ve set its value. After dynamically allocating space, we must dynamically free it: free(ptr); Use this command to clean up. Even though the program frees all memory on exit (or when main returns), don t be lazy! You never know when your main will get transformed into a subroutine! CS61C L05 Introduction to C (pt 3) (10)

Dynamic Memory Allocation (4/4) The following two things will cause your program to crash or behave strangely later on, and cause VERY VERY hard to figure out bugs: free()ing the same piece of memory twice calling free() on something you didn t get back from malloc() The runtime does not check for these mistakes Memory allocation is so performance-critical that there just isn t time to do this The usual result is that you corrupt the memory allocator s internal structure You won t find out until much later on, in a totally unrelated part of your code! CS61C L05 Introduction to C (pt 3) (11)

Binky Pointer Video (thanks to NP @ SU) CS61C L05 Introduction to C (pt 3) (12)

Arrays not implemented as you d think void foo() { int *p, *q, x, a[1]; // a[] = {3} also works here p = (int *) malloc (sizeof(int)); q = &x; } *p = 1; // p[0] would also work here *q = 2; // q[0] would also work here *a = 3; // a[0] would also work here printf("*p:%u, p:%u, &p:%u\n", *p, p, &p); printf("*q:%u, q:%u, &q:%u\n", *q, q, &q); printf("*a:%u, a:%u, &a:%u\n", *a, a, &a);... 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68... 52? 32? 2? 3?? 1... p q x a unnamed-malloc-space *p:1, p:52, &p:24 *q:2, q:32, &q:28 *a:3, a:36, &a:36 CS61C L05 Introduction to C (pt 3) (13)

C structures : Overview A struct is a data structure composed from simpler data types. Like a class in Java/C++ but without methods or inheritance. struct point { /* type definition */ int x; int y; }; void PrintPoint(struct point p) { printf( (%d,%d), p.x, p.y); } As always in C, the argument is passed by value a copy is made. struct point p1 = {0,10}; /* x=0, y=10 */ PrintPoint(p1); CS61C L05 Introduction to C (pt 3) (14)

C structures: Pointers to them Usually, more efficient to pass a pointer to the struct. The C arrow operator (->) dereferences and extracts a structure field with a single operator. The following are equivalent: struct point *p; /* code to assign to pointer */ printf( x is %d\n, (*p).x); printf( x is %d\n, p->x); CS61C L05 Introduction to C (pt 3) (15)

Kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta 1. Kind Meek Giggles Tease Peering Excited Zealous Youngsters. Yiding J 2. Kissing me gives tears per extra zebra YO! Peter D 3. Kiss me, gimme tea, persistently extol zee. You! Hava E 4. Kia Mechanics (are) Giant Terrible People Exclaiming Zealous Yodels. Gary M 5. Kiss me, gimme tea, pet exaltingly, zestful you. Hava E 6. Kid meets giant Texas people exercising zen-like yoga. -Rolf O 7. Kicking methods gives teaching people extra zest, youbetcha! Peter D 8. Kind men give ten percent extra, zestfully, youthfully. Hava E 9. Kissing Mentors Gives Testy Persistent Extremists Zealous Youthfulness. Gary M 10. Kindness means giving, teaching, permeating excess zeal yourself. Hava E 11. Kissing me gives ten percent extra zeal & youth! Dan (taking ideas from all) 1. Killing messengers gives terrible people exactly zero, yo 2. Kindergarten means giving teachers perfect examples (of) zeal (&) youth 3. Kissing mediocre girls/guys teaches people (to) expect zero (from) you 4. Kinky Mean Girls Teach Penis-Extending Zen Yoga 5. Kissing Mel Gibson, Teddy Pendergrass exclaimed: Zesty, yo! Dan Garcia CS61C L05 Introduction to C (pt 3) (16)

Pointer Arithmetic Peer Instruction Q How many of the following are invalid? I. pointer + integer II. integer + pointer III. pointer + pointer IV. pointer integer V. integer pointer VI. pointer pointer VII. compare pointer to pointer VIII. compare pointer to integer IX. compare pointer to 0 X. compare pointer to NULL CS61C L05 Introduction to C (pt 3) (17) #invalid 1 2 3 4 5 6 7 8 9 (1)0

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 L05 Introduction to C (pt 3) (19) I II III 0: - - - 1: - - YES 2: - YES - 3: - YES YES 4: YES - - 5: YES - YES 6: YES YES - 7: 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 L05 Introduction to C (pt 3) (20)

And in 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 L05 Introduction to C (pt 3) (21)

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 CS61C L05 Introduction to C (pt 3) (22)

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 L05 Introduction to C (pt 3) (23)

Linked List Example Let s look at an example of using structures, pointers, malloc(), and free() to implement a linked list of strings. /* node structure for linked list */ struct Node { char *value; struct Node *next; }; Recursive definition! CS61C L05 Introduction to C (pt 3) (24)

typedef simplifies the code struct Node { char *value; struct Node *next; }; String value; /* "typedef" means define a new type */ typedef struct Node NodeStruct; OR typedef struct Node { char *value; struct Node *next; } NodeStruct; /* Note similarity! */ /* To define 2 nodes */ THEN typedef NodeStruct *List; typedef char *String; struct Node { char *value; struct Node *next; } node1, node2; CS61C L05 Introduction to C (pt 3) (25)

Linked List Example /* Add a string to an existing list */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; { String s1 = "abc", s2 = "cde"; List thelist = NULL; thelist = cons(s2, thelist); thelist = cons(s1, thelist); /* or, just like (cons s1 (cons s2 nil)) */ thelist = cons(s1, cons(s2, NULL)); CS61C L05 Introduction to C (pt 3) (26)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node:? list: s: NULL "abc" CS61C L05 Introduction to C (pt 3) (27)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node:?? list: s: "abc" NULL CS61C L05 Introduction to C (pt 3) (28)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node: list:? "????" s: "abc" NULL CS61C L05 Introduction to C (pt 3) (29)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node: list:? "abc" s: "abc" NULL CS61C L05 Introduction to C (pt 3) (30)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node: list: s: NULL "abc" "abc" CS61C L05 Introduction to C (pt 3) (31)

Linked List Example /* Add a string to an existing list, 2nd call */ List cons(string s, List list) { List node = (List) malloc(sizeof(nodestruct)); } node->value = (String) malloc (strlen(s) + 1); strcpy(node->value, s); node->next = list; return node; node: "abc" s: "abc" NULL CS61C L05 Introduction to C (pt 3) (32)

Pointer Arithmetic Summary x = *(p+1)? x = *(p+1) ; x = *p+1? x = (*p) + 1 ; x = (*p)++? x = *p ; *p = *p + 1; x = *p++? (*p++)? *(p)++? *(p++)? x = *p ; p = p + 1; x = *++p? p = p + 1 ; x = *p ; Lesson? These cause more problems than they solve! CS61C L05 Introduction to C (pt 3) (33)

Kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta Kim s melodious giddiness terrifies people, excepting zealous yodelers Kirby Messed Gigglypuff Terribly, (then) Perfectly Exterminated Zelda and Yoshi Killed meat gives teeth peace except zebra yogurt Kind Men Give Tense People Extra Zeal (for) Yoga Killing melee gives terror; peace exhibits Zen yoga Young Zebras Exclaim, People Teach {Giraffes, Girls} Messy Kissing! Omar Akkawi King me, Gina tells Perry, expert zebra yodeler Diana Ko Kirk met Gibson s team, perilously expecting zealous youngsters Diana Ko Kind Men Give Ten Percent Expressly Zee Yoorphans Daniel Gallagher King Mel Gibson Tells People Examine Ze Yoodle! Daniel Gallagher Kizzle Meh Gizzle The Pezzle Exizzle Zeh Yo! Daniel Gallagher Killer Mechanical { Giraffe / Giant } Teaches Pet, Extinct Zebra, to Yodel Larry Ly Kilted Men Given Testosterone Perform Exceedingly Zealous Yoga David Wu CS61C L05 Introduction to C (pt 3) (34)