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

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

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

Arrays and Memory Management

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

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

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

Arrays and Pointers in C. Alan L. Cox

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

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

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

CS61C : Machine Structures

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

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

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

CS 61c: Great Ideas in Computer Architecture

C Arrays, Strings, More Pointers Instructor: Steven Ho

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

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

CS61C : Machine Structures

CS61C : Machine Structures

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

More C Pointer Dangers

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

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

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

Understanding Pointers

Fundamental of Programming (C)

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

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

C++ for Java Programmers

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

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

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

CS61C : Machine Structures

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

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

PRINCIPLES OF OPERATING SYSTEMS

CS61C : Machine Structures

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

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

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

A brief introduction to C programming for Java programmers

Incoming Exam. CS 201 Introduction to Pointers. What is a Pointer? Pointers and Addresses. High Speed Memory (RAM) Size of Variable Types.

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

Dynamic memory allocation (malloc)

Memory, Arrays & Pointers

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

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

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

Lectures 5-6: Introduction to C

Intermediate Programming, Spring 2017*

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

Lecture 2: C Programm

CS 61C: Great Ideas in Computer Architecture. Lecture 4: Memory Management. Bernhard Boser & Randy Katz

Memory Corruption 101 From Primitives to Exploit

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Kurt Schmidt. October 30, 2018

Intro to C: Pointers and Arrays

Arrays and Pointers (part 1)

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

Array Initialization

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

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

CS 11 C track: lecture 5

Arrays and Pointers (part 1)

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

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

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language and RISC-V Instruction Set Architecture

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

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

Principles of C and Memory Management

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

CS 61C: Great Ideas in Computer Architecture Intro to Assembly Language, MIPS Intro

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

CS 222: Pointers and Manual Memory Management

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

CS61, Fall 2012 Section 2 Notes

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

CS61C : Machine Structures

CS 0449 Sample Midterm

Lecture 04 Introduction to pointers

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

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

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Pointers in C/C++ 1 Memory Addresses 2

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

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

primitive arrays v. vectors (1)

CS 61c: Great Ideas in Computer Architecture

Transcription:

CS 61C: Great Ideas in Computer Architecture Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic & Logic Unit (ALU) Enable? Read/Write Address Write Data Read Data Memory Processor-Memory Interface Program Bytes Data Input Output I/O-Memory Interfaces 3 int a; a = -85; printf( %d, a); Computer Memory Do not confuse memory address and value. Nor a street address with the person living there. 4 Pointers C speak for memory addresses Notation int *x; // variable x is an address to an int int y = 9; // y is an int x = &y; // assign address of y to x // address operator int z = *x; // assign what x is pointing to to z // dereference operator *x = -7; // assign -7 to what x is pointing to What are the values of x, y, z? Pointer Type Pointers have types, like other variables type of object the pointer is pointing to Examples: int *pi; // pointer to int double *pd; // pointer to double char *pc; // pointer to char 5 6 1

Generic Pointer (void *) Generic pointer Points to any object (int, double, ) Does not know type of object it references (e.g. compiler does not know) Example: void *vp; // vp holds an address to // object of arbitrary type Applications Generic functions e.g. to allocate memory malloc, free accept and return pointers of any type see next lecture 7 Pointer to struct 8 Your Turn! Answer a b RED 3-7 GREEN 4 5 ORANGE -4 5-2 5 9 What s wrong with this Code? Output: a = 1853161526, p = 0x7fff5be57c08, *p = 0 10 Pointers as Function Arguments C passes arguments by value i.e. it passes a copy value does not change outside function To pass by reference use a pointer 11 Parameter Passing in Java primitive types (int, char, double) by value (i.e. passes a copy) Objects by reference (i.e. passes a pointer) Java uses pointers internally But hides them from the programmer Mapping of variables to addresses is not defined in Java language No address operator (&) Gives JVM flexibility to move stuff around 12 2

Your Turn! Answer a b c RED 5 3 1 GREEN 1 5 3 ORANGE 3 3 1 3 5 1 And in Conclusion, 14 Declaration: // allocate space // unknown content int a[5]; C Arrays // allocate & initialize int b = 3, 2, 1 ; Element access: b[1]; a[2] = 7; Index of first element: 0 15 Beware: no array bound checking! Output: a[0] = 1 a[1] = 2 a[2] = 3 a[3] = -1870523725 Often the result is much worse: erratic behavior segmentation fault, etc. C does not know array length! Pass as argument into functions 16 Use Constants, Not Literals Assign size to constant Bad pattern int i, ar[10]; for(i = 0; i < 10; i++)... Better pattern const int ARRAY_SIZE = 10; int i, a[array_size]; for(i = 0; i < ARRAY_SIZE; i++)... Single source of truth Avoiding maintaining two copies of the number 10 And the chance of changing only one DRY: Don t Repeat Yourself 17 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address Type declaration tells compiler how many bytes to fetch on each access through pointer E.g., 32-bit integer stored in 4 consecutive 8-bit bytes 16-bit short stored in two bytes short *y 32-bit integer stored in four bytes int *x char *z 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 Byte address 8-bit character stored in one byte 18 3

sizeof() operator sizeof(type) Returns number of bytes in object Number of bits in a byte is not standardized All modern computers: 8 bits per byte Some old computers use other values, e.g. 6 bits per byte By definition, in C sizeof(char)==1 For all other types result is hardware and compiler dependent Do not assume - Use sizeof! Output: double: 8 array: 20 s: 4 And in Conclusion, 19 20 So what did Dr. Moore Predict? Transistor* cost as a function of components per chip Minimum Shifts to right: As time passes, cost decreases provided we get more Fortunately we always had good ideas to use more: o Computers o Memory o Smartphones o Internet of Things? Why a minimum? If too small, some don t work! * Transistors: basic elements making up computers (see later) 21 Dr. Moore s Vision (in 1965) Something useful that is getting always better and less expensive is good for Society Business 22 Why do people say Moore s Law is over? Fabs (where chips are made) $5-10B Final Four: Intel TSMC Samsung Global Foundries (was IBM) 23 130nm 90nm 65nm Pointers 40nm 28nm <=22nm Lecture 3: 24 4

Break! And in Conclusion, 8/31/17 Fall 2017 - Lecture #3 25 26 Pointer Arithmetic - char Type Name Byte Addr* *pc = b c = 0x7fff50f54b3e pc = 0x7fff50f54b3f pc-c = 1 27 *Computer only uses byte addresses. Tables with blue headers are simplifications. Value Pointer Arithmetic - int Type Name Byte Addr *pi = 20 i = 0x7fff50f54b40 pi = 0x7fff50f54b44 pi-i = 1 28 Value Array Name / Pointer Duality Array variable is a pointer to the first (0 th ) element Can use pointers to access array elements char *pstr and char astr[] are nearly identical declarations Differ in subtle ways: astr++ is illegal Consequences: astr is an array variable, but works like a pointer astr[0] is the same as *astr astr[2] is the same as *(astr+2) Can use pointer arithmetic to access array elements 29 Arrays versus Pointer Example Output: a[1]=20, *(p+1)=20, p[2]=30 a[0]=11, a[1]=22, a[2]=33 Mixing pointer and array notation can be confusing à avoid. 30 5

Example: int n = 3; int *p; p += n; p -= n; Pointer Arithmetic // adds n*sizeof(int) to p // subtracts n*sizeof(int) from p Use only for arrays. Never: char *p; char a, b; p = &a; p += 1; // may point to b, or not Array» pointer to the initial (0th) array element a[i] º *(a+i) Arrays and Pointers An array is passed to a function as a pointer The array size (# of bytes) is lost! Passing arrays: explicitly Really int *array pass size int foo(int array[], unsigned int size) array[size - 1] int main(void) Usually bad style to interchange arrays and pointers int a[10], b[5]; foo(a, 10) foo(b, 5) 31 32 Arrays and Pointers int foo(int array[], unsigned int size) printf( %d\n, sizeof(array)); int main(void) int a[10], b[5]; foo(a, 10) foo(b, 5) printf( %d\n, sizeof(a)); What does this print?... because array is really a pointer (and a pointer is architecture-dependent, but likely to be 8 on modern 64-bit machines!) What does this print? 40 (provided sizeof(int)==4) 8 int i; int array[5]; for (i = 0; i < 5; i++) array[i] = ; int *p; int array[5]; for (p = array; p < &array[5]; p++) *p = ; Arrays and Pointers These code sequences have the same effect: Name Type Addr Value 33 34 Point 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 const int SZ = 10; int ar[sz], *p, *q, sum = 0; p = &ar[0]; q = &ar[sz]; 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 35 Valid Pointer Arithmetic Add/subtract an integer to/from a pointer Difference of 2 pointers (must both point to elements in same array) Compare pointers (<, <=, ==,!=, >, >=) Compare pointer to NULL (indicates that the pointer points to nothing) Everything makes no sense & is illegal: adding two pointers multiplying pointers subtract pointer from integer 36 6

Pointers to Pointers 37 Your Turn int x[] = 2, 4, 6, 8, 10 ; int *p = x; int **pp = &p; (*pp)++; (*(*pp))++; printf("%d\n", *p); Answer RED 2 GREEN 3 ORANGE 4 5 Name Type Addr Value 38 Administrivia Break! Homework 0 and Mini-bio will be released by tonight Lab swap policy is posted on Piazza and the website Guerrilla Session and mini-tutoring session details will be posted soon 39 8/31/17 Fall 2017 - Lecture #3 40 C Strings And in Conclusion, C strings are nullterminated character arrays char s[] = abc ; Type Name Byte Addr Value 41 42 7

String Example Concise strlen() int strlen(char *s) char *p = s; while (*p++) ; /* Null body of while */ return (p s 1); Output: str = abc, length = 3 What happens if there is no zero character at end of string? 43 44 Arguments in main() Example To get arguments to the main function, use: int main(int argc, char *argv[]) argc is the number of strings on the command line argv is a pointer to an array containing the arguments as strings UNIX: $ gcc -o ex Argc.c $./ex -g a "d e f arg[0] =./ex arg[1] = -g arg[2] = a arg[3] = d e f 45 46 And in Conclusion, And in Conclusion, Pointers are C speak for machine memory addresses Pointer variables are held in memory, and pointer values are just numbers that can be manipulated by software In C, close relationship between array names and pointers Pointers know the type & size of the object they point to (except void *) Like most things, pointers can be used for Pointers are powerful But, without good planning, a major source of errors Plenty of examples in the next lecture! 47 48 8