CS61C : Machine Structures

Similar documents
CS61C : Machine Structures

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

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

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 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. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

CS61C : Machine Structures

More C Pointer Dangers

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

ECE 15B COMPUTER ORGANIZATION

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

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

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

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

Lectures 13 & 14. memory management

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

CS 61c: Great Ideas in Computer Architecture

CS61C : Machine Structures

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

CS61C : Machine Structures

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

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

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

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

C Arrays, Strings, More Pointers Instructor: Steven Ho

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

Intro to C: Pointers and Arrays

Lecture 2: C Programm

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

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

Arrays and Memory Management

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

CS61C : Machine Structures

CSC C69: OPERATING SYSTEMS

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

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

Intermediate Programming, Spring 2017*

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

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

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

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

Pointers in C/C++ 1 Memory Addresses 2

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

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

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

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

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

CS61C : Machine Structures

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

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

CS 11 C track: lecture 5

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

CS61C : Machine Structures

CSC 1600 Memory Layout for Unix Processes"

Pointers and Arrays 1

Lecture 7: Procedures and Program Execution Preview

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

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

Heap Arrays and Linked Lists. Steven R. Bagley

Topics Introduction to Microprocessors

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C++ for Java Programmers

Heap Arrays. Steven R. Bagley

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

Introduction to C: Pointers

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

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

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

CPSC 213. Introduction to Computer Systems. Instance Variables and Dynamic Allocation. Unit 1c

CS24 Week 2 Lecture 1

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

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

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

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

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

Section Notes - Week 1 (9/17)

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

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

Pointers and References

QUIZ. What are 3 differences between C and C++ const variables?

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

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

Welcome! COMP s1. Programming Fundamentals

Pointers. Memory. void foo() { }//return

Understanding Pointers

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CS61C : Machine Structures

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

Kurt Schmidt. October 30, 2018

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

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

Transcription:

inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 Introduction to C (pt 2) 2014-09-08!!!Senior Lecturer SOE Dan Garcia!!!www.cs.berkeley.edu/~ddgarcia! C most popular! TIOBE programming has been tracking programming language popularity for the past decade, and C (in blue) is now on top! www.tiobe.com/index.php/content/paperinfo/tpci/! CS61C L04 Introduction to C (pt 2) (1)!

Enrollment update! Remember, all labs will use pair programming! (both partners must know stuff, tho!)! CS61C L04 Introduction to C (pt 2) (2)!

Review! All declarations go at the beginning of each function except if you use C99.! All data is in memory. Each memory location has an address to use to refer to it and a value stored in it.! A pointer is a C version of the address.! * follows a pointer to its value! & gets the address of a value! Only 0 (i.e., NULL) evaluate to FALSE.! CS61C L04 Introduction to C (pt 2) (3)!

More C Pointer Dangers! Declaring a pointer just allocates space to hold the pointer it does not allocate something to be pointed to!! Local variables in C are not initialized, they may contain anything.! What does the following code do?! void f()! {! int *ptr;! *ptr = 5;! }! CS61C L04 Introduction to C (pt 2) (4)!

Arrays (1/5)! Declaration:! int ar[2];!!declares a 2-element integer array. An array is really just a block of memory. int ar[] = {795, 635};!!declares and fills a 2-elt integer array.! Accessing elements:! ar[num]!!returns the num th element.! CS61C L04 Introduction to C (pt 2) (5)!

Arrays (2/5)! Arrays are (almost) identical to pointers! char *string and char string[] are nearly identical declarations! They differ in very subtle ways: incrementing, declaration of filled arrays! Key Concept: An array variable is a pointer to the first element.! CS61C L04 Introduction to C (pt 2) (6)!

Arrays (3/5)! Consequences:! ar is an array variable but looks like a pointer in many respects (though not all)! ar[0] is the same as *ar! ar[2] is the same as *(ar+2)! We can use pointer arithmetic to access arrays more conveniently.! Declared arrays are only allocated while the scope is valid!!char *foo() { char string[32];...; return string; } is incorrect! CS61C L04 Introduction to C (pt 2) (7)!

Arrays (4/5)! Array size n; want to access from 0 to n-1, so you should use counter AND utilize a variable for declaration & incr! Wrong int i, ar[10]; for(i = 0; i < 10; i++){... }! Right int ARRAY_SIZE = 10; int i, a[array_size]; for(i = 0; i < ARRAY_SIZE; i++){... }! Why? SINGLE SOURCE OF TRUTH! You re utilizing indirection and avoiding maintaining two copies of the number 10! CS61C L04 Introduction to C (pt 2) (8)!

Arrays (5/5)! Pitfall: An array in C does not know its own length, & bounds not checked!! Consequence: We can accidentally access off the end of an array.! Consequence: We must pass the array and its size to a procedure which is going to traverse it.! Segmentation faults and bus errors:! These are VERY difficult to find; be careful! (You ll learn how to debug these in lab )! CS61C L04 Introduction to C (pt 2) (9)!

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 L04 Introduction to C (pt 2) (10)!

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 L04 Introduction to C (pt 2) (11)!

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 L04 Introduction to C (pt 2) (12)!

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

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 L04 Introduction to C (pt 2) (14)!

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 L04 Introduction to C (pt 2) (15)!

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 L04 Introduction to C (pt 2) (16)!

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 L04 Introduction to C (pt 2) (17)!

Pointers in C! Why use pointers?! If we want to pass a huge 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 software, so be careful anytime you deal with them.! Dangling reference (use ptr before malloc)! Memory leaks (tardy free, lose the ptr)! CS61C L04 Introduction to C (pt 2) (18)!

Arrays not implemented as you d think! void foo() { int *p, *q, x; int a[4]; p = (int *) malloc (sizeof(int)); q = &x; *p = 1; // p[0] would also work here printf("*p:%u, p:%u, &p:%u\n", *p, p, &p);! *q = 2; // q[0] would also work here printf("*q:%u, q:%u, &q:%u\n", *q, q, &q);!!*a = 3; // a[0] would also work here printf("*a:%u, a:%u, &a:%u\n", *a, a, &a); }!..." 0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60..."?" 24" a" CS61C L04 Introduction to C (pt 2) (19)! 40"?" 20"?" 2"?" 3"?"?" 1"..." p q x" unnamed-malloc-space" *p:1, p:40, &p:12! *q:2, q:20, &q:16! *a:3, a:24, &a:24! K&R: An array name is not a variable!

Peer Instruction! Which are guaranteed to print out 5?! I: main() { int *a-ptr = (int *)malloc(int); *a-ptr = 5; printf( %d, *a-ptr); }! II:main() { int *p, a = 5; p = &a;... /* code; a,p NEVER on LEFT of = */ printf( %d, a); }! I II a) - - b) - YES c) YES - d) YES YES e) No idea! CS61C L04 Introduction to C (pt 2) (20)!

Binky Pointer Video (thanks to NP @ SU)! CS61C L04 Introduction to C (pt 2) (21)!

And in Conclusion! 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! Use handles to change pointers! Dynamically allocated heap memory must be manually deallocated in C.! Use malloc() and free() to allocate and deallocate memory from heap.! (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 L04 Introduction to C (pt 2) (22)!