04LecSp11CIntroIIx6 - 1/27/11 Levels of RepresentaSon/...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1/27/11 Levels of RepresentaSon/ InterpretaSon temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; High Level Language Program (e.g., C) CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduc)on to C (Part II) Compiler Assembly Language Program (e.g., MIPS) lw lw sw sw Assembler Machine Language Program (MIPS) Instructors: Randy H. Katz David A. PaGerson hGp://inst.eecs.Berkeley.edu/~cs61c/sp11 $t0, 0($2) $t1, 4($2) $t1, 0($2) $t0, 4($2) 0000 1010 1100 0101 1001 1111 0110 1000 1100 0101 1010 0000 We are here! Anything can be represented as a number, i.e., data or instrucSons 0110 1000 1111 1001 1010 0000 0101 1100 1111 1001 1000 0110 0101 1100 0000 1010 1000 0110 1001 1111 ! Machine Interpreta4on Hardware Architecture DescripCon (e.g., block diagrams) Architecture Implementa4on Logic Circuit DescripCon 1/27/11 Spring 2011  ­ ­ Lecture #4 1 1/27/11 (Circuit SchemaCc Diagrams) Spring 2011  ­ ­ Lecture #4 Agenda •  •  •  •  •  •  •  Peer InstrucSon QuesSon !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)} Arrays Administrivia Strings Pointer AllocaSon Technology Break Pointer Problems Summary 1/27/11 How many syntax + logic errors in this C code? Spring 2011  ­ ­ Lecture #4 3 1/27/11 Peer InstrucSon Answer errors in this C code? 1/27/11 Spring 2011  ­ ­ Lecture #4 Spring 2011  ­ ­ Lecture #4 #Errors Red: 1 Orange: 2 Green: 3 Yellow: 4 Pink: >4 4 Agenda #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);} How many syntax + logic 2 #Errors Red: 1 Orange: 2 Green: 3 Yellow: 4 Pink: >4 5 •  •  •  •  •  •  •  Arrays Administrivia Strings Pointer AllocaSon Technology Break Pointer Problems Summary 1/27/11 Spring 2011  ­ ­ Lecture #4 6 1 1/27/11 Arrays (1/5) Arrays (2/5) •  DeclaraSon: int ar[2]; declares a 2 ­element integer array: just a block of memory •  Arrays are (almost) idenScal to pointers –  char *string and char string are nearly idenScal declaraSons –  Differ in subtle ways: incremenSng, declaraSon of filled arrays int ar = {795, 635}; declares and iniSalizes a 2 ­element integer array •  Key Concept: Array variable is a “pointer” to the first (0th) element •  Accessing elements: ar[num] returns the numth element 1/27/11 Spring 2011  ­ ­ Lecture #4 7 1/27/11 Arrays (3/5) •  Array size n; want to access from 0 to n ­1, so you should use counter AND uSlize a variable for declaraSon & incrementaSon –  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 arithmeSc to conveniently access arrays –  Bad paGern int i, ar[10]; for(i = 0; i < 10; i++){ ... } –  BeGer paGern const int ARRAY_SIZE = 10 int i, a[ARRAY_SIZE]; for(i = 0; i < ARRAY_SIZE; i++){ ... } •  Declared arrays are only allocated while the scope is valid char *foo() { char string[32]; ...; return string; } •  SINGLE SOURCE OF TRUTH –  You’re uSlizing indirecSon and avoiding maintaining two copies of the number 10 is incorrect and very very bad Spring 2011  ­ ­ Lecture #4 8 Arrays (4/5) •  Consequences: 1/27/11 Spring 2011  ­ ­ Lecture #4 9 1/27/11 Arrays (5/5) Spring 2011  ­ ­ Lecture #4 10 Array Summary •  Pinall: 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 •  SegmentaSon faults and bus errors: •  Array indexing is syntacSc 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; –  These are VERY difficult to find; be careful! (You’ll learn how to debug these in lab) 1/27/11 Spring 2011  ­ ­ Lecture #4 11 1/27/11 Spring 2011  ­ ­ Lecture #4 12 2 1/27/11 Agenda •  •  •  •  •  •  Arrays Administrivia Strings Pointer AllocaSon Technology Break Pointer Problems 1/27/11 Spring 2011  ­ ­ Lecture #4 13 1/27/11 CS 61c in the News Google is hiring! And your knowledge of MapReduce is sure to impress them! Spring 2011  ­ ­ Lecture #4 14 Administrivia •  We have your pictures! –  file:///Users/randykatz/Documents/Courses/CS61C/ Sp11/Photos/cs61Pictures/classpage.html •  This week in lab and homework: –  Lab #2, MapReduce posted –  HW #2, Assembly Language posted (hws are leading the lecture – this is a good forcing funcSon to read ahead) •  Join the class discussion/announcements group! –  But don’t forget that some stuff is VERY easy to find on your own (e.g., arrow notaSon in C/C++) 1/27/11 Spring 2011  ­ ­ Lecture #4 15 1/27/11 Pointers and Structures struct Point { int x; int y; }; Point p1; Point p2; Point* paddr; /* dot notation */ int h = p1.x; p2.y = p1.y; •  •  •  •  •  •  •  /* arrow notation */ int h = paddr->x; int h = (*paddr).x; Spring 2011  ­ ­ Lecture #4 16 Agenda /* This works too */ p1 = p2; 1/27/11 Spring 2011  ­ ­ Lecture #4 17 Arrays Administrivia Strings Pointer AllocaSon Technology Break Pointer Problems Summary 1/27/11 Spring 2011  ­ ­ Lecture #4 18 3 1/27/11 C Strings Pointer ArithmeSc pointer + number •  String in C is just an array of characters char string = "abc"; •  How do you tell how long a string is? E.g., pointer + 1 adds 1 something to a pointer char char char –  Last character is followed by a 0 byte (aka “null terminator”) 19 ≡ *(a+i) •  An array is passed to a funcSon as a pointer –  The array size is lost! •  Usually bad style to interchange arrays and pointers –  Avoid pointer arithmeSc! 1/27/11 1/27/11 Must explicitly pass the size int foo(int array, unsigned int size) { … array[size - 1] … } int int main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … } Spring 2011  ­ ­ Lecture #4 i; array[10]; for (i = 0; i < 10; i++) { array[i] = …; } Spring 2011  ­ ­ Lecture #4 int foo(int array, unsigned int size) { … printf(“%d\n”, sizeof(array)); } 21 main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … printf(“%d\n”, sizeof(a)); } 1/27/11 Arrays and Pointers int int p = &a; 20 Arrays and Pointers Passing arrays: a[i] *p; a; b; Pointer arithme)c should be used cau)ously Arrays and Pointers Really int *array int int int p += 1; In each, p now points to b (Assuming compiler doesn’t reorder variables in memory) Adds 1*sizeof(char) Adds 1*sizeof(int) to the memory address to the memory address Spring 2011  ­ ­ Lecture #4 •  Array ≈ pointer to the iniSal (0th) array element *p; a; b; p = &a; p += 1; int strlen(char s) { int n = 0; while (s[n] != 0) n++; return n; } 1/27/11 pointer – number What does this print? 8 ... because array is really a pointer (and a pointer is architecture dependent, but likely to be 8 on modern machines!) What does this print? 40 Spring 2011  ­ ­ Lecture #4 22 Pointer ArithmeSc (1/2) •  Since a pointer is just a memory address, we can add to it to step through an array •  p+1 correctly computes a ptr to the next array element automaScally depending on sizeof (type) •  *p++ vs. (*p)++ ? int *p; int array[10]; for (p = array; p < &array[10]; p++) { *p = …; } x = *p++ ⇒ x = *p; p = p + 1; x = (*p)++ ⇒ x = *p; *p = *p + 1; This is a C syntax/seman)cs thing These code sequences have the same effect! •  What if we have an array of large structs (objects)? –  C takes care of it in the same way it handles arrays 1/27/11 Spring 2011  ­ ­ Lecture #4 23 1/27/11 Spring 2011  ­ ­ Lecture #4 24 4 1/27/11 Pointer ArithmeSc (2/2) Peer InstrucSon int main(void){ int A = {5,10}; int *p = A; •  Every addiSon or subtracSon to a pointer steps the number of bytes of thing it is declared to point to –  This is why type ­casSng can get you into trouble –  1 byte for a char, 4 bytes for an int, etc. } •  Following are equivalent: { return (array[n]); // OR... return *(array + n); } Spring 2011  ­ ­ Lecture #4 25 1/27/11 Spring 2011  ­ ­ Lecture #4 Peer InstrucSon int main(void){ int A = {5,10}; int *p = A; } 5 10 A[0] A[1] p •  If the first prinn outputs 100 5 5 10, what will the next two prinn output? Red a) 101 10 5 10 then 101 11 5 11 Orange b) 104 10 5 10 then 104 11 5 11 Green c) 101 <other> 5 10 then 101 <3 ­others> Yellow d) 104 <other> 5 10 then 104 <3 ­others> Pink e) One of the two prinns causes an ERROR Spring 2011  ­ ­ Lecture #4 27 •  •  •  •  •  •  Arrays and Strings Administrivia Pointer AllocaSon Technology Break Pointer Problems Summary 1/27/11 Pointers & AllocaSon (1/2) 28 •  PoinSng to something that already exists: –  int *ptr; –  int *ptr, var1, var2; var1 = 5; ptr = &var1; var2 = *ptr; •  ptr doesn’t actually point to anything yet (points somewhere, but don’t know where). We can either: •  var1 and var2 have space implicitly allocated for them –  Make it point to something that already exists, or –  Allocate room in memory for something new that it will point to … Spring 2011  ­ ­ Lecture #4 Spring 2011  ­ ­ Lecture #4 Pointers & AllocaSon (2/2) •  Ayer declaring a pointer: 1/27/11 26 Agenda printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); p = p + 1; printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); *p = *p + 1; printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); 1/27/11 p printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); p = p + 1; printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); *p = *p + 1; printf(“%u %d %d %d\n”, p, *p, A[0], A[1]); •  If the first prinn outputs 100 5 5 10, what will the next two prinn output? Red a) 101 10 5 10 then 101 11 5 11 Orange b) 104 10 5 10 then 104 11 5 11 Green c) 101 <other> 5 10 then 101 <3 ­others> Yellow d) 104 <other> 5 10 then 104 <3 ­others> Pink e) One of the two prinns causes an ERROR int get(int array, int n) 1/27/11 5 10 A[0] A[1] 29 ptr 1/27/11 ? 5 var1 ? Spring 2011  ­ ­ Lecture #4 5 var2 ? 30 5 1/27/11 Arrays (one element past array must be valid) •  Array size n; want to access from 0 to n ­1, but test for exit by comparing to address one element past the array int 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? Pointer ArithmeSc •  What is valid pointer arithmeSc? –  Add an integer to a pointer –  Subtract 2 pointers (in the same array) –  Compare pointers (<, <=, ==, !=, >, >=) –  Compare pointer to NULL (indicates that the pointer points to nothing) •  Everything else is illegal since it makes no sense: –  Adding two pointers –  MulSplying pointers –  Subtract pointer from integer •  C defines that one element past end of array must be a valid address, i.e., will not cause an bus error or address error 1/27/11 Spring 2011  ­ ­ Lecture #4 31 1/27/11 Spring 2011  ­ ­ Lecture #4 32 Pointer ArithmeSc Summary Pointer ArithmeSc to Copy Memory •  x = *(p+1) ? •  We can use pointer arithmeSc to “walk” through memory: ⇒ x = *(p+1); •  x = *p+1 ? void copy(int *from, int *to, int n) { int i; for (i=0; i<n; i++) { *to++ = *from++; } } ⇒ x = (*p) + 1 ; •  x = (*p)++ ? ⇒ x = *p ; *p = *p + 1; •  x = *p++ ? (*p++) ? *(p)++ ? *(p++) ? ⇒ x = *p ; p = p + 1; ⇒ p = p + 1 ; x = *p ; •  x = *++p ? •  Lesson? –  Using anything but the standard *p++ , (*p)++ causes more problems than it solves! • Note we had to pass size (n) to copy 1/27/11 Spring 2011  ­ ­ Lecture #4 33 1/27/11 Pointer ArithmeSc: Peer InstrucSon QuesSon 1/27/11 Spring 2011  ­ ­ Lecture #4 35 Pointer ArithmeSc Peer InstrucSon Answer How many of the following are invalid? How many of the following are invalid? I.  pointer + integer II.  integer + pointer III.  pointer + pointer IV.  pointer – integer V.  integer – pointer VI.  pointer – pointer VII.  compare pointer to pointer VIII.  compare pointer to integer IX.  compare pointer to 0 X.  compare pointer to NULL Spring 2011  ­ ­ Lecture #4 #invalid Red: 1 Orange: 2 Green: 3 Yellow: 4 Pink: 5 36 I.  II.  III.  IV.  V.  VI.  VII.  VIII.  IX.  X.  1/27/11 pointer + integer integer + pointer pointer + pointer pointer – integer integer – pointer pointer – pointer compare pointer to pointer compare pointer to integer compare pointer to 0 compare pointer to NULL ptr + 1 1 + ptr ptr + ptr ptr  ­ 1 1  ­ ptr ptr  ­ ptr ptr1 == ptr2 ptr == 1 ptr == NULL ptr == NULL Spring 2011  ­ ­ Lecture #4 #invalid Red: 1 Orange: 2 Green: 3 Yellow: 4 Pink: 5 37 6 1/27/11 C FuncSons C FuncSons •  Give name of funcSon and type of value it returns int max(a, b, c) /* declaration */ int a, b, c; /* type of params */ { int m; m = (a>b)? a:b; return(m>c? m:c); } •  FuncSons: How to structure C programs for understandability and reuse •  Calling funcSon: s = max(x,y,100); •  If no value to return, declare it type void –  FuncSon with no return value called procedure in other programming languages 1/27/11 Spring 2011  ­ ­ Lecture #4 38 1/27/11 Pointers and FuncSons (1/4) •  Solved by passing in a pointer to our subrouSne. •  Now what gets printed? y=5 void AddOne(int *p) { *p = *p + 1; } int y = 5; AddOne(y); printf(“y = %d\n”, y); 1/27/11 40 1/27/11 Pointers and FuncSons (3/4) *p) int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); printf(“*q = %d\n”, *q); Spring 2011  ­ ­ Lecture #4 *q = 50 60 41 •  SoluSon! Pass a pointer to a pointer, declared as **h •  Now what gets printed? void IncrementPtr(int **h) *q = 60 { *h = *h + 1; } q Aq Aq 50 Spring 2011  ­ ­ Lecture #4 Pointers and FuncSons (4/4) •  But what if the thing you want changed is a pointer? •  What gets printed? 1/27/11 y=6 int y = 5; AddOne(&y); printf(“y = %d\n”, y); Spring 2011  ­ ­ Lecture #4 void IncrementPtr(int { p = p + 1; } 39 Pointers and FuncSons (2/4) •  SomeSmes you want to have a procedure increment a variable … •  What gets printed? void AddOne(int x) { x = x + 1; } Spring 2011  ­ ­ Lecture #4 70 42 int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); printf(“*q = %d\n”, *q); 1/27/11 Spring 2011  ­ ­ Lecture #4 50 60 70 43 7 1/27/11 C String Standard FuncSons #include <string.h> Agenda •  int strlen(char *string); •  •  •  •  •  •  –  Compute the length of string •  int strcmp(char *str1, char *str2); –  Return 0 if str1 and str2 are idenScal (how is this different from str1 == str2?) •  char *strcpy(char *dst, char *src); –  Copy contents of string src to the memory at dst. Caller must ensure that dst has enough memory to hold the data to be copied –  Note: dst = src only copies pointers, not string itself 1/27/11 Spring 2011  ­ ­ Lecture #4 44 Agenda •  •  •  •  •  •  Spring 2011  ­ ­ Lecture #4 1/27/11 –  A fatal failure in the execuSon of a machine language instrucSon resulSng from the processor detecSng an anomalous condiSon on its bus. Such condiSons include invalid address alignment (accessing a mulS ­byte number at an odd address), accessing a physical address that does not correspond to any device, or some other device ­specific hardware error. A bus error triggers a processor ­level excepSon which Unix translates into a “SIGBUS” signal which, if not caught, will terminate the current process. •  SegmentaSon Fault –  An error in which a running Unix program aGempts to access memory not allocated to it and terminates with a segmentaSon violaSon error and usually a core dump. 46 1/27/11 Spring 2011  ­ ­ Lecture #4 47 C String Problems •  Common mistake is to forget to allocate an extra byte for the null terminator •  More generally, C requires the programmer to manage memory manually (unlike Java or C++) •  Unlike Java, C lets you cast a value of any type to any other type without performing any checking int x = 1000; int *p = x; /* invalid */ int *q = (int *) x; /* valid */ •  First pointer declaraSon is invalid since the types do not match •  Second declaraSon is valid C but is almost certainly wrong –  When creaSng a long string by concatenaSng several smaller strings, the programmer must insure there is enough space to store the full string! –  What if you don’t know ahead of Sme how big your string will be? –  Buffer overrun security holes! –  Is it ever correct? Spring 2011  ­ ­ Lecture #4 45 •  http://www.hyperdictionary.com/ •  Bus Error C Pointer Dangers 1/27/11 Spring 2011  ­ ­ Lecture #4 SegmentaSon Fault vs. Bus Error Pointers and Strings Administrivia Pointer AllocaSon Technology Break Pointer Problems Summary 1/27/11 Pointers and Strings Administrivia Pointer AllocaSon Technology Break Pointer Problems Summary 48 1/27/11 Spring 2011  ­ ­ Lecture #4 49 8 1/27/11 More Common C Errors And in Conclusion, … •  Difference between assignment and equality a=b a == b is assignment is an equality test •  One of the most common errors for beginning C programmers! –  One paGern (when comparing with constant) is to put the var on the right! If you happen to use =, it won’t compile! •  Pointers are aliases to variables •  Pointers can be used to index into arrays •  Strings are (null terminated) arrays of characters •  Pointers are the source of many bugs in C, so handle with care •  if (3 == a) { ... 1/27/11 Spring 2011  ­ ­ Lecture #4 50 1/27/11 Spring 2011  ­ ­ Lecture #4 51 9 ...
View Full Document

Ask a homework question - tutors are online