CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II. Control. Consider memory to be a single huge array

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

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

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

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

Intro to C: Pointers and Arrays

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

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

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

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

Arrays and Memory Management

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

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

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

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

CS61C : Machine Structures

CS61C : Machine Structures

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

CS 102 Computer Architecture. Lecture 2: Introduction to C, Part I. Instructor: Sören Schwertfeger.

CS61C : Machine Structures

CS 61c: Great Ideas in Computer Architecture

ECE 15B COMPUTER ORGANIZATION

More C Pointer Dangers

Arrays and Pointers in C. Alan L. Cox

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

CS61C : Machine Structures

C Arrays, Strings, More Pointers Instructor: Steven Ho

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

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

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

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

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

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

C++ for Java Programmers

CS61C : Machine Structures

Topics Introduction to Microprocessors

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

CS61C : Machine Structures

Operators and Control Flow. CS449 Fall 2017

CS61C : Machine Structures

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

CS61C : Machine Structures

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 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C : Machine Structures

Intermediate Programming, Spring 2017*

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

CS 61C: Great Ideas in Computer Architecture Lecture 2: Introduction to C, Part I

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

377 Student Guide to C++

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

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CS61C : Machine Structures

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

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

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output }

Pointers in C/C++ 1 Memory Addresses 2

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CS61C : Machine Structures

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

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

CS 61c: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture Introduction to C

Pointers and References

CS61C : Machine Structures

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

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

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

9/9/12. New- School Machine Structures (It s a bit more complicated!) CS 61C: Great Ideas in Computer Architecture IntroducMon to Machine Language

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Lecture 2, September 4

Dynamic memory allocation (malloc)

First of all, it is a variable, just like other variables you studied

Lecture 2: C Programm

CSC 1600 Memory Layout for Unix Processes"

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Class Information ANNOUCEMENTS

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

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Kurt Schmidt. October 30, 2018

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

Lecture 04 Introduction to pointers

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

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

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

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

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

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

REFERENCES, POINTERS AND STRUCTS

CMSC 341 Lecture 2 Dynamic Memory and Pointers

Transcription:

Review: Components of a Computer CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II Processor Control Datapath PC Enable? Read/Write Address Memory Program Bytes Input Instructors: Krste Asanovic & Vladimir Stojanovic hbp://inst.eecs.berkeley.edu/~cs61c/sp15 Registers ArithmeMc & Logic Unit (ALU) Write Data Read Data Data Output 1 Processor- Memory Interface I/O- Memory Interfaces 2 Address vs. Value Consider memory to be a single huge array Each cell of the array has an address associated with it Each cell also stores some value Do you think they use signed or unsigned numbers? NegaMve address?! Don t confuse the address referring to a memory locamon with the value stored there... 101 102 103 104 105... 23 42... Poers An address refers to a parmcular memory locamon; e.g., it pos to a memory locamon Poer: A variable that contains the address of a variable LocaMon (address) name... 101 102 103 104 105... 23 42 104... x y p 3 4 Poer Syntax *x;! Tells compiler that variable x is address of an! x = &y;! Tells compiler to assign address of y to x! & called the address operator in this context! z = *x;! Tells compiler to assign value at address in x to z! * called the dereference operator in this context! CreaMng and Using Poers How to create a poer: & operator: get address of a variable *p, x; p? x? x = 3; p? x 3 p = &x; p x 3 How get a value poed to? * (dereference operator): get the value that the poer pos to!prf( p pos to %d\n,*p);! Note the * gets used 2 different ways in this example. In the declaramon to indicate that p is going to be a poer, and in the prf to get the value poed to by p. 5 6 1

Using Poer for Writes How to change a variable poed to? Use the dereference operator * on leh of assignment operator = Poers and Parameter Passing Java and C pass parameters by value Procedure/funcMon/method gets a copy of the parameter, so changing the copy cannot change the original *p = 5; p x 3 p x 5 void add_one ( x)! x = x + 1;! y = 3;! add_one(y);! y remains equal to 3 7 8 Poers and Parameter Passing How can we get a funcmon to change the value held in a variable? void add_one ( *p)!*p = *p + 1;! y = 3;! add_one(&y);! y is now equal to 4 Types of Poers Poers are used to po to any kind of data (, char, a struct, a poer, etc.) Normally a poer only pos to one type (, char, a struct, etc.). void * is a type that can po to anything (generic poer) Use void * sparingly to help avoid program bugs, and security issues, and other bad things! 9 10 More C Poer Dangers Declaring a poer just allocates space to hold the poer does not allocate thing being poed to! Local variables in C are not inimalized, they may contain anything (aka garbage ) What does the following code do? void f() *ptr; *ptr = 5; 11 tyepdef struct x; y; Po; Po p1; Po p2; Po *paddr; Poers and Structures /* dot notation */ h = p1.x; p2.y = p1.y; /* arrow notation */ h = paddr->x; h = (*paddr).x; /*structure assignment*/ p2 = p1; Note, C structure assignment is not a deep copy. All members are copied, but not things poed to by members. 12 2

Poers in C Why use poers? If we want to pass a large struct or array, it s easier / faster / etc. to pass a poer than the whole thing Want to modify an object, not just pass its value In general, poers allow cleaner, more compact code So what are the drawbacks? Poers are probably the single largest source of bugs in C, so be careful anymme you deal with them Most problemamc with dynamic memory management coming up next lecture Dangling references and memory leaks Why Poers in C? At Mme C was invented (early 1970s), compilers ohen didn t produce efficient code Computers 25,000 Mmes faster today, compilers beber C designed to let programmer say what they want code to do without compiler gepng in way Even give compiler hs which registers to use! Today, many applicamons abain acceptable performance using higher- level languages without poers Low- level system code smll needs low- level access via poers, hence conmnued popularity of C 13 14 Clickers/Peer InstrucMon Time void foo( *x, *y)! t;! if ( *x > *y ) t = *y; *y = *x; *x = t;!! a=3, b=2, c=1;! foo(&a, &b);! foo(&b, &c);! foo(&a, &b);! prf("a=%d b=%d c=%d\n", a, b, c);!! Result is: A: a=3 b=2 c=1! B: a=1 b=2 c=3! C: a=1 b=3 c=2! D: a=3 b=3 c=3! E: a=1 b=1 c=1! 15 Administrivia We can accommodate all those on the wait list, but you have to enroll in a lab secmon with space! Lab secmon is important, but you can abend different discussion secmon Enroll o lab with space, and try to swap with someone later HW0 due 11:59:59pm Sunday 2/1 Right aher the Superbowl Midterm- II now Thursday April 9 in class 16 DeclaraMon: ar[2]; C Arrays declares a 2- element eger array: just a block of memory ar[] = 795, 635; declares and inimalizes a 2- element eger array returns the num th element C Strings 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 (aka null terminator ) strlen(char s[]) n = 0; while (s[n]!= 0) n++; return n; 17 18 3

Array Name / Poer Duality Key Concept: Array variable is a poer to the first (0 th ) element So, array variables almost idenmcal to poers char *string and char string[] are nearly idenmcal declaramons Differ in subtle ways: incremenmng, declaramon of filled arrays Consequences: ar is an array variable, but looks like a poer ar[0] is the same as *ar ar[2] is the same as *(ar+2) Can use poer arithmemc to conveniently access arrays Changing a Poer Argument? What if want funcmon to change a poer? What gets pred? void inc_ptr( *p)! p = p + 1;!! A[3] = 50, 60, 70;! *q = A;! inc_ptr( q);! prf( *q = %d\n, *q);! *q = 50! A! q! 50! 60! 70! 19 Poer to a Poer SoluMon! Pass a poer to a poer, declared as **h! Now what gets pred? void inc_ptr( **h)! *h = *h + 1;!! A[3] = 50, 60, 70;! *q = A;! inc_ptr(&q);! prf( *q = %d\n, *q);! *q = 60! A! q! q! 50! 60! 70! C Arrays are Very PrimiMve An array in C does not know its own length, and its bounds are not checked! Consequence: We can accidentally access off the end of an array Consequence: We must pass the array and its size to any procedure that is going to manipulate it SegmentaMon faults and bus errors: These are VERY difficult to find; be careful! (You ll learn how to debug these in lab) 22 Use Defined Constants Array size n; want to access from 0 to n- 1, so you should use counter AND umlize a variable for declaramon & incrementamon Bad pabern i, ar[10]; for(i = 0; i < 10; i++)... BeBer pabern const ARRAY_SIZE = 10 i, a[array_size]; for(i = 0; i < ARRAY_SIZE; i++)... Accessing elements: ar[num] SINGLE SOURCE OF TRUTH You re umlizing indirecmon and avoiding maaining two copies of the number 10 DRY: Don t Repeat Yourself 23 PoinMng to Different Size Objects Modern machines are byte- addressable Hardware s memory composed of 8- bit storage cells, each has a unique address A C poer is just abstracted memory address Type declaramon tells compiler how many bytes to fetch on each access through poer E.g., 32- bit eger stored in 4 consecumve 8- bit bytes 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 Byte address 16- bit short stored in two bytes short *y! 32- bit eger stored in four bytes *x! 8- bit character stored in one byte char *z! 24 4

sizeof() operator sizeof(type) returns number of bytes in object But number of bits in a byte is not standardized In olden Mmes, when dragons roamed the earth, bytes could be 5, 6, 7, 9 bits long By definimon, sizeof(char)==1 Can take sizeof(arr), or sizeof(strucbype) We ll see more of sizeof when we look at dynamic memory management Poer ArithmeMc poer + number poer number e.g., poer + 1 adds 1 something to a poer char *p; char a; char b; p = &a; p += 1; Adds 1*sizeof(char) to the memory address In each, p now pos to b (Assuming compiler doesn t reorder variables in memory. Never code like this!!!!) *p; a; b; p = &a; p += 1; Adds 1*sizeof() to the memory address Poer arithme)c should be used cau)ously 25 26 Arrays and Poers Array poer to the inimal (0th) array element a[i] *(a+i) An array is passed to a funcmon as a poer The array size is lost! Usually bad style to erchange arrays and poers Avoid poer arithmemc! Passing arrays: Really *array Must explicitly pass the size foo( array[], unsigned size) array[size - 1] main(void) a[10], b[5]; foo(a, 10) foo(b, 5) Arrays and Poers foo( array[], unsigned size) prf( %d\n, sizeof(array)); main(void) a[10], b[5]; foo(a, 10) foo(b, 5) prf( %d\n, sizeof(a)); What does this pr?... because array is really a poer (and a poer is architecture dependent, but likely to be 8 on modern machines!) What does this pr? 8 40 27 28 i; array[10]; for (i = 0; i < 10; i++) array[i] = ; Arrays and Poers *p; array[10]; for (p = array; p < &array[10]; p++) *p = ; These code sequences have the same effect! Clickers/Peer InstrucMon Time x[5] = 2, 4, 6, 8, 10 ;! *p = x;! **pp = &p;! (*pp)++;! (*(*pp))++;! prf("%d\n", *p);! Result is: A: 2 B: 3 C: 4 D: 5 E: None of the above 29 30 5

In the News (1/23/2015): Google Exposing Apple Security Bugs Google security published details of three bugs in Apple OS X (90 days aher privately nomfying Apple) One network stack problem fixed in Yosemite, all in next beta One is dereferencing a null poer! One is zeroing wrong part of memory! Separately, Google announces it won t patch WebKit vulnerability affecmng Android 4.3 and below (only about 930 million acmve users) Concise strlen() strlen(char *s) char *p = s; while (*p++) ; /* Null body of while */ return (p s 1); What happens if there is no zero character at end of string? 31 32 Po past end of array? Array size n; want to access from 0 to n-1, but test for exit by comparing to address one element past the array ar[10], *p, *q, sum = 0;... p = &ar[0]; q = &ar[10]; while (p!= q) /* sum = sum + *p; p = p + 1; */ sum += *p++; Is this legal? C defines that one element past end of array must be a valid address, i.e., not cause an error Valid Poer ArithmeMc Add an eger to a poer. Subtract 2 poers (in the same array) Compare poers (<, <=, ==,!=, >, >=) Compare poer to NULL (indicates that the poer pos to nothing) Everything else illegal since makes no sense: adding two poers mulmplying poers subtract poer from eger Arguments in main()! To get arguments to the main funcmon, use: main( argc, char *argv[])! What does this mean? argc contains the number of strings on the command line (the executable counts as one, plus one for each argument). Here argc is 2: unix% sort myfile argv is a poer to an array containing the arguments as strings Example! foo hello 87! argc = 3 /* number arguments */ argv[0] = "foo", argv[1] = "hello", argv[2] = "87"! Array of poers to strings 35 36 6

And In Conclusion, Poers are abstracmon of machine memory addresses Poer variables are held in memory, and poer values are just numbers that can be manipulated by sohware In C, close relamonship between array names and poers Poers know the type of the object they po to (except void *) Poers are powerful but potenmally dangerous 37 7