CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Lecturer SOE Dan Garcia www.cs.berkeley.edu/~ddgarcia inst.eecs.berkeley.edu/~cs61c CS61C.

Slides:



Advertisements
Similar presentations
CS61CL L01 Introduction (1) Huddleston, Summer 2009 © UCB Introduction to C Jeremy Huddleston inst.eecs.berkeley.edu/~cs61c.
Advertisements

Dynamic Memory Management
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
C Programming - Lecture 5
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
CS61C L03 Introduction to C (pt 2) (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS 61C L04 C Pointers (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2007 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L3 C Pointers (1) Garcia, Fall 2005 © UCB Lecturer PSOE, new dad Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS61C L05 Introduction to C (pt 3) (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L3 C Pointers (1) Beamer, Summer 2007 © UCB Scott Beamer, Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – C Strings,
CS61C L06 C Memory Management (1) Garcia, Spring 2007 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C :
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2008 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS61C L05 Introduction to C (pt 3) (1) Garcia, Spring 2007 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
CS61C L06 C Memory Management (1) Garcia, Fall 2006 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS 61C L03 C Pointers (1)Garcia / Patterson Fall 2002 © UCB CS61C - Machine Structures Lecture 3 C pointers  Dan Garcia (
CS61C L03 Introduction to C (pt 1) (1) Garcia, Fall 2011 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CS61C L3 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 – More C intro,
CS61CL L01 Introduction (1) Huddleston, Summer 2009 © UCB Jeremy Huddleston inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS 61C L04 C Pointers (1) Garcia, Spring 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
Instructor: Justin Hsia 6/26/2013Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: John Wawrzynek & Vladimir Stojanovic
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: Krste Asanovic & Vladimir Stojanovic
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Instructor: Justin Hsia 6/20/2012Summer Lecture #31 CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver 1.
CS61C L04 Introduction to C (pt 2) (1) Garcia, Spring 2010 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C.
Dynamic Allocation in C
Computer Organization and Design Pointers, Arrays and Strings in C
Day 03 Introduction to C.
IT 252 Computer Organization and Architecture
ENEE150 Discussion 07 Section 0101 Adam Wang.
Checking Memory Management
Instructor Paul Pearce
Lecturer SOE Dan Garcia
C help session: Tonight 306 Soda
Inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 – Introduction to C (pt 3) C Memory Management Lecturer SOE Dan Garcia.
CS61C - Machine Structures Lecture 4 C Structures Memory Management
Hello to Scott Sloan from Superior, WI!
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
March, 2006 Saeid Nooshabadi
SPL – PS2 C++ Memory Handling.
Presentation transcript:

CS61C L04 Introduction to C (pt 2) (1) Garcia, Fall 2011 © UCB Lecturer SOE Dan Garcia inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 – Introduction to C (pt 2) Quantum Processor  UCSB have produced the first Quantum processor with memory that can be used to store instructions and data! (ala what von Neumann did in 1940s)

CS61C L04 Introduction to C (pt 2) (2) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB Pointers (1/4) Sometimes you want to have a procedure increment a variable? What gets printed? void AddOne(int x) { x = x + 1; } int y = 5; AddOne( y); printf(“y = %d\n”, y); y = 5 …review…

CS61C L04 Introduction to C (pt 2) (10) Garcia, Fall 2011 © UCB Pointers (2/4) Solved by passing in a pointer to our subroutine. Now what gets printed? void AddOne(int *p) { *p = *p + 1; } int y = 5; AddOne(&y); printf(“y = %d\n”, y); y = 6 …review…

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

CS61C L04 Introduction to C (pt 2) (12) Garcia, Fall 2011 © UCB 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 = A q q

CS61C L04 Introduction to C (pt 2) (13) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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 free s 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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) Garcia, Fall 2011 © UCB 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); } ?? 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” a 24 ?

CS61C L04 Introduction to C (pt 2) (19) Garcia, Fall 2011 © UCB 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); } Peer Instruction I II a) - - b) - YES c) YES - d) YES YES e) No idea

CS61C L04 Introduction to C (pt 2) (20) Garcia, Fall 2011 © UCB Binky Pointer Video (thanks to SU)

CS61C L04 Introduction to C (pt 2) (21) Garcia, Fall 2011 © UCB “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!”