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

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

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

Intro to C: Pointers and Arrays

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

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

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

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

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

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

CS61C : Machine Structures

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

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

More C Pointer Dangers

CS61C : Machine Structures

CS61C : Machine Structures

CS61C : Machine Structures

CS61C : Machine Structures

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

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

CS61C : Machine Structures

CS61C : Machine Structures

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

ECE 15B COMPUTER ORGANIZATION

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

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

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!

CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduc)on to C (Part I) We are here!

Topics Introduction to Microprocessors

CS61C : Machine Structures

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

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

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

CS61C : Machine Structures

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 Introduc=on to C, Part I. We are here!

C: Introduction, Pointers Instructors: Steven Ho, Nick Riasanovsky

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

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

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

CS 61c: Great Ideas in Computer Architecture

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

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

Lecture 2: C Programm

Arrays and Memory Management

CS61C : Machine Structures

CS61C : Machine Structures

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

Lecture 2: Memory in C

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers

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

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

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

Class Information ANNOUCEMENTS

Memory, Data, & Addressing II

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

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

Memory, Data, & Addressing II CSE 351 Spring

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

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

Programming Languages and Techniques (CIS120)

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer

EL2310 Scientific Programming

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

C++ for Java Programmers

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

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Kurt Schmidt. October 30, 2018

CS61C : Machine Structures

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

CS 61C: Great Ideas in Computer Architecture Strings and Func.ons. Anything can be represented as a number, i.e., data or instruc\ons

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

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

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

Arrays and Pointers in C. Alan L. Cox

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

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

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

C Programming Primer 8/31/15 1

Memory Management. CS449 Fall 2017

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

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

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

CSE 374 Programming Concepts & Tools

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

printf( Please enter another number: ); scanf( %d, &num2);

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

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

Hardware: Logical View

Number Representation & I See The C

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

Outline. Pointers arithme.c and others Func.ons & pointers

Lecture Notes on Memory Layout

Lecture 3: C Programm

Introduction to Scientific Computing and Problem Solving

Programming in C. What is C?... What is C?

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Transcription:

Agenda CS 61C: Great Ideas in Computer Architecture Introduc;on to C, Part II Instructors: Krste Asanovic Randy H. Katz hep://inst.eecs.berkeley.edu/~cs61c/f12 Review Pointers Administrivia Arrays Technology Break Summary Fall 2012 - - Lecture #5 1 Fall 2012 - - Lecture #5 2 Review C is a popular and efficient compiled language used for systems programming and applica;on development Deriva;ves include C++, Objec;ve- C, C# Java borrowed much of the basic syntax Very close to machine, so some;mes difficult to program and debug Key concepts last ;me: compila;on, preprocessor, typed data and func;ons, main(), structs, enums, control flow 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? Nega;ve address?! Don t confuse the address referring to a memory loca;on with the value stored there... 101 102 103 104 105... 23 42... Fall 2012 - - Lecture #5 3 Fall 2012 - - Lecture #5 4 Pointers An address refers to a par;cular memory loca;on; e.g., it points to a memory loca;on Pointer: A variable that contains the address of a variable Loca;on (address) name... 101 102 103 104 105... 23 42 104... x y p Pointer Syntax int *x;! Tells compiler that variable x is address of an int! 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! Fall 2012 - - Lecture #5 5 Fall 2012 - - Lecture #5 6 1

Crea;ng and Using Pointers How to create a pointer: & operator: get address of a variable int *p, x; p? x? x = 3; p? x 3 p = &x; p x 3 How get a value pointed to? * (dereference operator): get the value that the pointer points to!printf( p points to %d\n,*p);! Note the * gets used 2 different ways in this example. In the declara;on to indicate that p is going to be a pointer, and in the printf to get the value pointed to by p. Using Pointer for Writes How to change a variable pointed to? Use the dereference operator * on len of assignment operator = *p = 5; p x 3 p x 5 Fall 2012 - - Lecture #5 7 Fall 2012 - - Lecture #5 8 Pointers and Parameter Passing Java and C pass parameters by value Procedure/func;on/method gets a copy of the parameter, so changing the copy cannot change the original void addone (int x) {! x = x + 1;! int y = 3;! addone(y);! y remains equal to 3 Pointers and Parameter Passing How can we get a func;on to change the value held in a variable? void addone (int *p) {!*p = *p + 1;! int y = 3;! addone(&y);! y is now equal to 4 Fall 2012 - - Lecture #5 9 Fall 2012 - - Lecture #5 10 Types of Pointers Pointers are used to point to any kind of data (int, char, a struct, etc.) Normally a pointer only points to one type (int, char, a struct, etc.). void * is a type that can point to anything (generic pointer) Use sparingly to help avoid program bugs, and security issues, and other bad things! More C Pointer Dangers Declaring a pointer just allocates space to hold the pointer it does not allocate the thing being pointed to! Local variables in C are not ini;alized, they may contain anything (aka garbage ) What does the following code do? void f() { int *ptr; *ptr = 5; Fall 2012 - - Lecture #5 11 Fall 2012 - - Lecture #5 12 2

struct Point { int x; int y; ; Point p1; Point p2; Point *paddr; Pointers and Structures /* dot notation */ int h = p1.x; p2.y = p1.y; /* arrow notation */ int h = paddr->x; int h = (*paddr).x; /* This works too */ p1 = p2; Pointers in C Why use pointers? If we want to pass a large struct or array, it s easier / faster / etc. to pass a pointer than the whole thing In general, pointers allow cleaner, more compact code So what are the drawbacks? Pointers are probably the single largest source of bugs in C, so be careful any;me you deal with them Most problema;c with dynamic memory management which you will to know by the end of the semester, but not for the projects (there will be a lab later in the semester) Dangling references and memory leaks Fall 2012 - - Lecture #5 13 Fall 2012 - - Lecture #5 14 Why Pointers in C? At ;me C was invented (early 1970s), compilers onen didn t produce efficient code Computers 25,000 ;mes faster today, compilers beeer C designed to let programmer say what they want code to do without compiler gesng in way Even give compilers hints which registers to use! S;ll useful for low- level system code Today s compilers produce much beeer code, so may not need to use pointers Compilers even ignore hints since they do it beeer! How many logic and syntax errors? 1 2 3 void main(); { int *p, x=5, y; // init y = *(p = &x) + 1; int z; flip-sign(p); printf("x=%d,y=%d,p=%d\n",x,y,p); flip-sign(int *n){*n = -(*n) Fall 2012 - - Lecture #5 15 16 Peer Instruc;on Answer #insert <stdio.h> void main(); { int *p, x=5, y; // init y = *(p = &x) + 1; int z; flip-sign(p); printf("x=%d,y=%d,p=%d\n",x,y,*p); flip-sign(int *n){*n = -(*n); 5 syntax + logic errors in this C code What is output aner correct errors? x=5,y=6,p=-5 x=-5,y=6,p=-5! x=-5,y=4,p=-5! void main(); { int *p, x=5, y; // init int z; y = *(p = &x) + 1; flip-sign(p); printf("x=%d,y=%d,p=%d\n", x,y,*p); flip-sign(int *n) {*n = -(*n); Fall 2012 - - Lecture #5 17 18 3

Administrivia HW #2 Lab #2 No Discussion sec;ons this week, but extra office hours 19 Extra Office Hours This Week (Alan Christopher: Tue 5-7 320 Soda) Loc Do: Fri 12-2pm Qualcomm Cyber Café (James Ferguson: Tue 10-11 AM & 1-2 PM, 320 Soda) Anirudh Garg: Wed 4-6 Qualcomm Cyber Café William Ku: 6-8 Thursday 283E Soda Brandon Luong: Wed 6-8 283E Soda Ravi Punj: Wed 12-2 Free Speech Movement Cafe. Sung Roa Yoon: Thu 7-9 283E Soda. Watch Piazza! 20 The Rules (and we really mean it!) Arrays (1/5) Declara;on: int ar[2]; declares a 2- element integer array: just a block of memory int ar[] = {795, 635; declares and ini;alizes a 2- element integer array Accessing elements: ar[num] returns the num th element Fall 2012 - - Lecture #1 21 Fall 2012 - - Lecture #5 22 Arrays (2/5) C Strings C arrays are (almost) iden;cal to pointers char *string and char string[] are nearly iden;cal declara;ons Differ in subtle ways: incremen;ng, declara;on of filled arrays End of C string marked by 0 in last character Key Concept: Array variable is a pointer to the first (0 th ) element Fall 2012 - - Lecture #5 23 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 ) int strlen(char s[]) { int n = 0; while (s[n]!= 0) n++; return n; Fall 2012 - - Lecture #5 24 4

Arrays (3/5) Consequences: ar is an array variable, but looks like a pointer ar[0] is the same as *ar ar[2] is the same as *(ar+2) We can use pointer arithme;c to conveniently access arrays Declared arrays are only allocated while the scope is valid char *foo() { char string[32];...; return string; is incorrect and very very bad Arrays (4/5) Array size n; want to access from 0 to n- 1, so you should use counter AND u;lize a variable for declara;on & incrementa;on Bad paeern int i, ar[10]; for(i = 0; i < 10; i++){... BeEer paeern int ARRAY_SIZE = 10 int i, a[array_size]; for(i = 0; i < ARRAY_SIZE; i++){... SINGLE SOURCE OF TRUTH You re u;lizing indirec;on and avoiding maintaining two copies of the number 10 DRY: Don t Repeat Yourself Fall 2012 - - Lecture #5 25 Fall 2012 - - Lecture #5 26 Arrays (5/5) Pi{all: 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 Segmenta;on faults and bus errors: These are VERY difficult to find; be careful! (You ll learn how to debug these in lab) Array Summary Array indexing is syntac;c sugar for pointers a[i] is treated as *(a+i) E.g., three equivalent ways to zero an array: for (i=0; i < size; i++) a[i] = 0; for (i=0; i < size; i++) *(a+i) = 0; for (p=a; p < a+size; p++) *p = 0; IncremenGng a pointer makes it point to the next variable in memory (type of pointer says how big each variable is) Fall 2012 - - Lecture #5 27 Fall 2012 - - Lecture #5 28 What is TRUE about this func;on? void foo(char *s, char *t) { while (*s) s++; while (*s++ = *t++) It has syntax errors ; No syntax errors; it changes characters in string t to next character in the string s No syntax errors; it copies a string at address t to the string at address s! Ques;on: Which statement is FALSE regarding C and Java? Arrays in C are just pointers to the 0- th element As Java was derived from C, it has the same control flow constructs Like Java, in C you can check the length of an array ( a.length gives no. elements in a) 29 30 5

FYI Update to ANSI C C99 or C9X standard gcc -std=c99 to compile References http://en.wikipedia.org/wiki/c99! http://home.tiscalinet.ch/t_wolf/tw/c/ c9x_changes.html! Highlights Declara;ons in for loops, like Java Java- like // comments (to end of line) Variable- length non- global arrays <inttypes.h>: explicit integer types <stdbool.h>: for boolean logic types and defini;ons And In Conclusion, All data is in memory Each memory loca;on has an address to use to refer to it and a value stored in it Pointer is a C version (abstrac;on) of a data address * follows a pointer to its value & gets the address of a value Arrays and strings are implemented as varia;ons on pointers C is an efficient language, but leaves safety to the programmer Array bounds not checked Variables not automa;cally ini;alized Use pointers with care: they are a common source of bugs in programs Fall 2012 - - Lecture #5 31 Fall 2012 - - Lecture #5 32 6