04LecSp12CIntroIIx6 - 1/26/12 Agenda •  •  • ...

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/26/12 Agenda •  •  •  •  •  •  •  •  CS 61C: Great Ideas in Computer Architecture Introduc)on to C, Part II Instructor: David A. Pa>erson h>p://inst.eecs.Berkeley.edu/~cs61c/sp12 1/26/12 Spring 2012  ­ ­ Lecture #4 1 New ­School Machine Structures (It’s a bit more complicated!) Harness 1/26/12 Achieve High Performance Compiler Assembly Language Program (e.g., MIPS) >1 instrucJon @ one Jme e.g., 5 pipelined instrucJons Core Memory (Cache) Input/Output •  Parallel Data InstrucJon Unit(s) >1 data item @ one Jme e.g., Add of 4 pairs of words Today’s Logic Gates 3 1100 0101 1010 0000 0110 1000 1111 1001 1010 0000 0101 1100 1111 1001 1000 0110 0101 1100 0000 1010 1000 0110 1001 1111 ! Logic Circuit DescripCon 1/26/12 (Circuit SchemaCc Diagrams) Spring 2012  ­ ­ Lecture #4 4 Arrays (1/5) •  All data is in memory •  DeclaraJon: int ar[2]; declares a 2 ­element integer array: just a block of memory –  Each memory locaJon has an address to use to refer to it and a value stored in it •  Pointer is a C version (abstracJon) of a data address –  * “follows” a pointer to its value –  & gets the address of a value int ar = {795, 635}; declares and iniJalizes a 2 ­element integer array •  C is an efficient language, but leaves safety to the programmer –  Array bounds not checked –  Variables not automaJcally iniJalized –  Use pointers with care: they are a common source of bugs in programs Spring 2012  ­ ­ Lecture #3 1001 1111 0110 1000 Architecture Implementa4on Review 1/26/12 0000 1010 1100 0101 Anything can be represented as a number, i.e., data or instrucJons Hardware Architecture DescripCon (e.g., block diagrams) Cache Memory •  Programming Languages Lecture 1/26/12 Spring 2012  ­ ­ Lecture #4 $t0, 0($2) $t1, 4($2) $t1, 0($2) $t0, 4($2) We are here! Machine Interpreta4on Core FuncJonal Unit(s) A0+B0 A1+B1 A2+B2 A3+B3 •  Hardware descripJons All gates @ one Jme … Core lw lw sw sw Assembler Machine Language Program (MIPS) Computer •  Parallel InstrucJons 2 temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; High Level Language Program (e.g., C) Smart Phone Warehouse Scale Computer •  Parallel Threads Parallelism & Assigned to core e.g., Lookup, Ads Spring 2012  ­ ­ Lecture #4 Big Idea #1: Levels of RepresentaJon/ InterpretaJon So0ware Hardware •  Parallel Requests Assigned to computer e.g., Search “Katz” Arrays Pointer arithmeJc Administrivia Arrays vs. pointers Technology Break Pointer Problems CriJcisms of C Summary 5 •  Accessing elements: ar[num] returns the numth element 1/26/12 Spring 2011  ­ ­ Lecture #4 6 1 1/26/12 Arrays (2/5) C Strings •  Arrays are (almost) idenJcal to pointers –  char *string and char string are nearly idenJcal declaraJons –  Differ in subtle ways: incremenJng, declaraJon of filled arrays –  End of C string marking by 0 in last character •  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”) •  Key Concept: Array variable is a “pointer” to the first (0th) element 1/26/12 Spring 2011  ­ ­ Lecture #4 7 1/26/12 Arrays (3/5) 8 •  Array size n; want to access from 0 to n ­1, so you should use counter AND uJlize a variable for declaraJon & incrementaJon –  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 arithmeJc to conveniently access arrays –  Bad pa>ern int i, ar[10]; for(i = 0; i < 10; i++){ ... } –  Be>er pa>ern 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 uJlizing indirecJon and avoiding maintaining two copies of the number 10 –  DRY: “Don’t Repeat Yourself” is incorrect and very very bad Spring 2011  ­ ­ Lecture #4 Spring 2012  ­ ­ Lecture #4 Arrays (4/5) •  Consequences: 1/26/12 int strlen(char s) { int n = 0; while (s[n] != 0) n++; return n; } 9 1/26/12 Arrays (5/5) Spring 2011  ­ ­ Lecture #4 10 Array Summary •  Piuall: 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 •  SegmentaJon faults and bus errors: •  Array indexing is syntacJc 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/26/12 Spring 2011  ­ ­ Lecture #4 11 1/26/12 Spring 2011  ­ ­ Lecture #4 12 2 1/26/12 What is TRUE about this funcJon? ☐ ☐ ☐ void foo(char *s, char *t) { while (*s) s++; It has syntax errors while (*s++ = *t++) ; } QuesJon: Which statement is FALSE regarding C and Java? ☐ 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! ☐ ☐ ☐ 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) ☐ 13 14 Pointer ArithmeJc pointer + number Arrays and Pointers Passing arrays: pointer – number •  Array ≈ pointer to the iniJal (0th) array element E.g., pointer + 1 adds 1 something to a pointer char char char *p; a; b; int int int p = &a; p += 1; *p; a; b; a[i] p = &a; p += 1; –  The array size is lost! •  Usually bad style to interchange arrays and pointers –  Avoid pointer arithmeJc! Pointer arithme)c should be used cau)ously Spring 2012  ­ ­ Lecture #4 15 1/26/12 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)); } 1/26/12 Spring 2012  ­ ­ Lecture #4 What does this print? Must explicitly pass the size int main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … } Spring 2012  ­ ­ Lecture #4 16 Arrays and Pointers int int 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? *(a+i) •  An array is passed to a funcJon as a pointer 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 1/26/12 ≡ Really int *array int foo(int array, unsigned int size) { … array[size - 1] … } i; array[10]; for (i = 0; i < 10; i++) { array[i] = …; } int *p; int array[10]; for (p = array; p < &array[10]; p++) { *p = …; } These code sequences have the same effect! 40 17 1/26/12 Spring 2012  ­ ­ Lecture #4 18 3 1/26/12 Administrivia Get to Know Your Professor •  CS61c is relentless! •  Started it last semester, and was popular on the surveys •  More than lecture automatons? –  This week: Lab #2, HW #2 –  Lab #2, Amazon EC2 –  HW #2 will soon be posted •  TA Sco> Beamer guest lecture 1/31 •  Due to conflicts with CS188, will start midtem at 6:40; ends at 9:40 •  Wonderful to see the valuable discussion and help going on in Piazza! 1/26/12 Spring 2012  ­ ­ Lecture #3 19 1/26/12 Spring 2012  ­ ­ Lecture #4 MS BA PhD Agenda David Pa>erson History •  Oldest of large family (4 kids) •  Married High School Sweetheart at 19 •  •  •  •  •  •  •  •  El Camino College DP 1st Home •  UCLA BA Math @ 21 •  1st college graduate •  Father at 21 –  2nd child in grad school •  UCLA PhD @ 29 South High School DP 2nd Home •  Joined Cal in 1977 21 Arrays Administrivia Pointer arithmeJc Arrays vs. pointers Technology Break Pointer Problems CriJcisms of C Summary 1/26/12 Spring 2012  ­ ­ Lecture #4 Pointer ArithmeJc (1/2) x = *p++ ⇒ x = *p; p = p + 1; x = (*p)++ ⇒ x = *p; *p = *p + 1; This is a C syntax/seman)cs thing •  Every addiJon or subtracJon to a pointer steps the number of bytes of thing it is declared to point to –  This is why type ­casJng can get you into trouble –  1 byte for a char, 4 bytes for an int, etc. •  Following are equivalent: int get(int array, int n) { return (array[n]); // OR... return *(array + n); •  What if we have an array of large structs (objects)? –  C takes care of it in the same way it handles arrays Spring 2012  ­ ­ Lecture #4 22 Pointer ArithmeJc (2/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 automaJcally depending on sizeof (type) •  *p++ vs. (*p)++ ? 1/26/12 20 23 1/26/12 } Spring 2012  ­ ­ Lecture #4 24 4 1/26/12 Pointers & AllocaJon (1/2) If the first prinu outputs 100 5 5 10, what will the next two prinu output? ☐ ☐ ☐ 101 10 5 10 101 11 5 11 104 10 5 10 104 11 5 11 101 <other> 5 10 101 <3 ­others>! ☐ int main(void){ int A = {5,10}; int *p = A; 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]); } 5 10 A[0] A[1] p 25 •  PoinJng to something that already exists: –  int *ptr, var1, var2; var1 = 5; ptr = &var1; var2 = *ptr; •  var1 and var2 have space implicitly allocated for them 1/26/12 ? 5 var1 ? 5 var2 ? Spring 2012  ­ ­ Lecture #4 27 –  Make it point to something that already exists, or –  Allocate room in memory for something new that it will point to … 1/26/12 Spring 2012  ­ ­ Lecture #4 26 •  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? 1/26/12 Spring 2012  ­ ­ Lecture #4 28 Pointer ArithmeJc to Copy Memory •  What is valid pointer arithmeJc? •  We can use pointer arithmeJc to “walk” through memory: –  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) void copy(int *from, int *to, int n) { int i; for (i=0; i<n; i++) { *to++ = *from++; } } •  Everything else is illegal since it makes no sense: –  Adding two pointers –  MulJplying pointers –  Subtract pointer from integer Spring 2012  ­ ­ Lecture #4 •  ptr doesn’t actually point to anything yet (points somewhere, but don’t know where). We can either: •  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 Pointer ArithmeJc 1/26/12 –  int *ptr; Arrays (one element past array must be valid) Pointers & AllocaJon (2/2) ptr •  A|er declaring a pointer: • Note we had to pass size (n) to copy 29 1/26/12 Spring 2012  ­ ­ Lecture #4 30 5 1/26/12 Arrays vs. Pointers Which one of the pointer arithmeJc operaJons is INVALID? •  Array name is a read ­only pointer to the 0th element of the array •  Array parameter can be declared as an array or a pointer; an array argument can be passed as a pointer int strlen(char s) int { { int n = 0; while (s[n] != 0) n++; return n; } } Could be wri>en: while (s[n]) 1/26/12 strlen(char *s) int n = 0; while (s[n] != 0) n++; return n; Spring 2012  ­ ­ Lecture #4 ☐ Pointer + pointer ☐ Pointer – integer ☐ Integer + pointer ☐ 31 33 Pointers and FuncJons (1/2) Which one of the pointer comparisons is INVALID? ☐ ☐ •  What if the thing you want changed is a pointer? •  What gets printed? Compare pointer to pointer Compare pointer to integer ☐ void IncrementPtr(int { p = p + 1; } Compare pointer to 0 int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); printf(“*q = %d\n”, *q); ☐ 34 1/26/12 •  SoluJon! Pass a pointer to a pointer, declared as **h •  Now what gets printed? void IncrementPtr(int **h) *q = 60 { *h = *h + 1; } q Aq 1/26/12 Spring 2012  ­ ­ Lecture #4 50 60 *q = 50 Aq 50 60 70 Spring 2012  ­ ­ Lecture #4 35 C String Standard FuncJons #include <string.h> Pointers and FuncJons (2/2) int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); printf(“*q = %d\n”, *q); *p) •  int strlen(char *string); –  Compute the length of string •  int strcmp(char *str1, char *str2); –  Return 0 if str1 and str2 are idenJcal (how is this different from str1 == str2?) •  char *strcpy(char *dst, char *src); 70 36 –  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/26/12 Spring 2012  ­ ­ Lecture #4 37 6 1/26/12 SegmentaJon Fault vs. Bus Error C String Problems •  http://www.hyperdictionary.com/ •  Bus Error –  A fatal failure in the execuJon of a machine language instrucJon resulJng from the processor detecJng an anomalous condiJon on its bus. Such condiJons include invalid address alignment (accessing a mulJ ­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 excepJon which Unix translates into a “SIGBUS” signal which, if not caught, will terminate the current process. •  SegmentaJon Fault –  An error in which a running Unix program a>empts to access memory not allocated to it and terminates with a segmentaJon violaJon error and usually a core dump. 1/26/12 Spring 2012  ­ ­ Lecture #4 38 •  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++) –  When creaJng a long string by concatenaJng several smaller strings, the programmer must insure there is enough space to store the full string! –  What if you don’t know ahead of Jme how big your string will be? –  Buffer overrun security holes! 1/26/12 CriJcisms of C  ­ Syntax –  x & 1 == 0 means x & (1 == 0) 
 ! ! ! ! ! ! !vs. (x & 1) == 0! •  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 pa>ern (when comparing with constant) is to put the var on the right! If you happen to use =, it won’t compile! •  15 levels of precedence for 45 operators –  K&R p. 53 –  Therefore use () •  if (3 == a) { ... Spring 2012  ­ ­ Lecture #4 40 1/26/12 CriJcisms of C  ­ Syntax 41 •  Case statement (switch) requires proper placement of break to work properly –  if (a=b) is true if a ≠ 0 a|er assignment –  Will do all cases unJl sees a break •  Syntax: *p++ means get value at address pointed to by p, then increment p to point to next data item •  *--p means decrement p to point to the previous data item and that value Spring 2012  ­ ­ Lecture #4 Spring 2012  ­ ­ Lecture #4 CriJcisms of C  ­ Syntax •  Syntax: confusion about = and ==! 1/26/12 39 CriJcisms of C  ­ Syntax •  K&R: C, like any other language, has its blemishes. Some of the operators have the wrong precedence; some parts of the syntax could be beOer. •  Precedence: == binds more Jghtly than &, |! 1/26/12 Spring 2012  ­ ­ Lecture #4 switch(ch){ ! case ‘+’: … /* does + and - */! case ‘-’: … break;! case ‘*’: … break;! default: …! }! 42 1/26/12 Spring 2012  ­ ­ Lecture #4 43 7 1/26/12 CriJcisms of C – Type casJng CriJcisms of C  ­ FuncJonality •  Type casJng  ­ pretend that a variable declared in one type is actually of another type int x, y, *p; …! y = *p; /* legal */! y = *x; /* illegal */! y = *((int *)x); /* legal! */! •  No runJme checking of array bounds 1/26/12 1/26/12 Spring 2012  ­ ­ Lecture #4 44 C in Retrospect Spring 2012  ­ ­ Lecture #4 45 And in Conclusion, … •  C is not a “very high level” language, nor a “big” one, and is not specialized to any par)cular area of applica)on. But its absence of restric)ons and its generality make it more convenient and effec)ve for many tasks than supposedly more powerful languages. •  C is close to hardware so ideal for 61C vs. Java or Python, since trying to understand hardware and performance •  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 •  C, like all languages, has flaws but its small and useful language for some tasks 1/26/12 1/26/12 –  Kernighan and Ritchie Spring 2012  ­ ­ Lecture #3 46 Spring 2012  ­ ­ Lecture #4 47 8 ...
View Full Document

Ask a homework question - tutors are online