36
Compsci 250 / ECE 250: “C Programming” Alvin R. Lebeck Some slides based on those from Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem

Computer Science, Computer Architecture

Embed Size (px)

DESCRIPTION

Duke Computer Architecture

Citation preview

Page 1: Computer Science, Computer Architecture

Compsci 250 / ECE 250: “C Programming”

Alvin R. Lebeck Some slides based on those from Daniel Sorin,

Andrew Hilton, Amir Roth, Gershon Kedem

Page 2: Computer Science, Computer Architecture

2 © Alvin R. Lebeck From Sorin, Hilton, Roth

Administrivia

•  Homework #1 •  No class Monday

•  Today !  Finish Data Representations !  C programming & Memory

•  Updated Academic Honesty Policy !  Do not provide solutions to any archive (digital, paper, etc.) !  This is a simple extension of existing policy of not providing

solutions to another student.

Compsci / ECE 250

Page 3: Computer Science, Computer Architecture

3 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Review: Answer

What floating-point number is 0xC1580000? 1100 0001 0101 1000 0000 0000 0000 0000

1 1000 0010 101 1000 0000 0000 0000 0000 0 22 23 30 31

S N M

•  Sign = 1 means this is a negative number •  Exponent = (128+2)-127 = 3 •  Mantissa = 1.1011 •  -1.1011x23 = -1101.1 = -13.5

Page 4: Computer Science, Computer Architecture

4 © Alvin R. Lebeck From Sorin, Hilton, Roth

Special values in IEEE Floating Point

•  How do you represent 0.0 in IEEE Floating Point? !  0.0 = 000000000 !  But need 1.XXXXX representation?

•  Exponent = 0 is denormalized !  Implicit 0. instead of 1. in mantissa !  Allows 0000….0000 to be 0 !  Helps with very small numbers near 0

•  Results in +/- 0 in FP (but they are �equal�)

Compsci / ECE 250

Page 5: Computer Science, Computer Architecture

5 © Alvin R. Lebeck From Sorin, Hilton, Roth

Other Weird FP numbers

•  Exponent = 1111 1111 also not standard !  If all 0 mantissa: +/- ∞

1/0 = +∞ -1/0 = -∞

!  If non zero mantissa: Not a Number (NaN)

sqrt(-42) = NaN

Compsci / ECE 250

Page 6: Computer Science, Computer Architecture

6 © Alvin R. Lebeck From Sorin, Hilton, Roth

FP Addition/Substraction

•  Addition/Subtraction !  Align the exponents !  Perform operation !  Renormalize the result (put into 1.M x 2E-127 form)

•  What can possibly go wrong? •  Well a lot •  Search for disasters caused by numerical errors

Compsci / ECE 250

Page 7: Computer Science, Computer Architecture

7 © Alvin R. Lebeck From Sorin, Hilton, Roth

Software Implication! Rounding Errors

•  We only have 32-bits to represent floats !  Must approximate some values

•  Limited bits for mantissa •  Does (x+y)*z = (x*z+y*z)? •  Mathematically yes, but assumes infinite precision •  Assume base 10, four digits available (two to left, two to

right of decimal point) !  x = 99.96 x 103

!  x = x + 0.07 !  x = 100.03 x 103 !  x = 10.00 x 104

•  Numerical Analysis (CS 220) studies some of these issues

Compsci / ECE 250

Page 8: Computer Science, Computer Architecture

8 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Floating Point Representation

•  Double Precision Floating point: 64-bit representation: !  1-bit sign !  11-bit (biased) exponent !  52-bit fraction (with implicit 1).

•  �double� in Java, C, C++, …

1 11-bit 52 - bit Exp S Mantissa

Page 9: Computer Science, Computer Architecture

9 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

ASCII Character Representation 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g 150 h 151 i 250 j 153 k 154 l 155 m 156 n 157 o 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del

Oct. Char

•  Each character represented by 7-bit ASCII code (packed into 8-bits) •  Convert upper to lower case ‘A’ + 3210 = ‘a’ •  Other tables with decimal and HEX values.

Page 10: Computer Science, Computer Architecture

10 © Alvin R. Lebeck From Sorin, Hilton, Roth

Unicode

•  Many types •  UTF-8: variable length encoding backward compatible

with ASCII !  Linux

•  UTF-16: variable length !  Windows, Java

•  UTF-32: fixed length

Compsci / ECE 250

Page 11: Computer Science, Computer Architecture

11 © Alvin R. Lebeck From Sorin, Hilton, Roth

Data Representation Summary

•  Need efficient representations •  2’s complement for signed integers •  IEEE Floating Point for Real numbers •  Bits are bits are bits, same bits can be interpreted as

different types (unsigned, 2’s complement, float, etc.) •  Next up: C programming & memory

Compsci / ECE 250

Page 12: Computer Science, Computer Architecture

12 © Alvin R. Lebeck From Sorin, Hilton, Roth

What you know today

Compsci / ECE 250

• JAVA ... System.out.println("Please Enter In Your First Name: "); String firstName = bufRead.readLine(); System.out.println("Please Enter In The Year You Were Born: "); String bornYear = bufRead.readLine(); System.out.println("Please Enter In The Current Year: "); String thisYear = bufRead.readLine(); int bYear = Integer.parseInt(bornYear); int tYear = Integer.parseInt(thisYear); int age = tYear – bYear ; System.out.println("Hello " + firstName + ". You are " + age + " years old");

Page 13: Computer Science, Computer Architecture

13 © Alvin R. Lebeck From Sorin, Hilton, Roth

How does a Java program execute?

•  Compile Java Source to Java Byte codes •  Java Virtual Machine (JVM) interprets/translates Byte

codes •  JVM is a program executing on the hardware… •  Java has lots of things that make it easier to program

without making mistakes •  JVM handles memory for you

!  What do you do when you remove an entry from a hash table, binary tree, etc.?

Compsci / ECE 250

Page 14: Computer Science, Computer Architecture

14 © Alvin R. Lebeck From Sorin, Hilton, Roth

The C Programming Language

•  No virtual machine !  No dynamic type checking, array bounds, garbage collection, etc. !  Compile source file directly to machine (this is a little simplified)

•  Closer to hardware !  Easier to make mistakes !  Can often result in faster code

•  Generally used for ‘systems programming’ !  operating systems, embedded systems, database implementation !  There is object oriented C++ (C is a strict subset of C++)

Compsci / ECE 250

Page 15: Computer Science, Computer Architecture

15 © Alvin R. Lebeck From Sorin, Hilton, Roth

The C Programming Language (Continued)

•  No objects •  Procedural, not object oriented

!  No objects with methods

•  Structures, unions like objects !  Member variables (no methods)

•  Pointers – memory, arrays •  External standard library – I/O, other facilities •  Macro preprocessor (#<directive>) •  Additional Resources

!  Kernighan & Richie book The C Programming Language !  MIT open course Practical Programming in C link in ‘docs’ of web

site !  Drew Hilton Video Snippets

Compsci / ECE 250

Page 16: Computer Science, Computer Architecture

16 © Alvin R. Lebeck From Sorin, Hilton, Roth

Compiling and Running a C Program

•  Use the gcc program to create an executable file •  gcc –o <outputname> <source file name> •  gcc –o hello hello.c (must be in same directory as hello.c) •  If no –o option, then default output name is a.out (e.g., gcc hello.c) •  Type the program name on the command line

!  ./ before “hello” means look in current directory for hello program

Compsci / ECE 250

Page 17: Computer Science, Computer Architecture

17 © Alvin R. Lebeck From Sorin, Hilton, Roth

Debugging

•  Print debugging… !  Just output information at different points in the program !  Not the most efficient, but often works.

•  gdb <executable filename> •  Good for stopping at set points in program and inspecting

variable values. !  If you get good at using a debugger it is easier/better than printf

debugging… !  See GDB Essentials video off https://www.cs.duke.edu/courses/

spring15/compsci250/docs.html

Compsci / ECE 250

Page 18: Computer Science, Computer Architecture

18 © Alvin R. Lebeck From Sorin, Hilton, Roth

Variables, operators, expressions

•  C variables are similar to Java !  Data types: int, float, double, char, void !  Signed and unsigned int !  char, short, int, long, long long can all be integer types

»  These specify how many bits to represent an integer

•  Constants !  Use #define C preprocessor !  E.g.,: #define MAX_SCORE 100

•  Operators: !  Mathematical +, -, *, /, %, !  Logical !, &&, ||, ==, !=, <, >, <=, >= !  Bitwise &, |, ~, ^ , <<, >> (we’ll get to these next)

•  Expressions: var1 = var2 + var3;

Compsci / ECE 250

Page 19: Computer Science, Computer Architecture

19 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Bitwise AND / OR / XOR

•  & operator performs bitwise AND •  | operator performs bitwise OR •  ^ operator performs bitwise Exclusive OR (XOR) •  ~ operator performs bitwise NOT •  Per bit

0 & 0 = 0 0 | 0 = 0 0 ^ 0 = 0 0 & 1 = 0 0 | 1 = 1 0 ^ 1 = 1 1 & 0 = 0 1 | 0 = 1 1 ^ 0 = 1 1 & 1 = 1 1 | 1 = 1 1 ^ 1 = 0

•  For multiple bits, apply operation to individual bits in same position

011010 101110 001010

011010 101110 111110

AND OR 011010 101110 110100

XOR

Page 20: Computer Science, Computer Architecture

20 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

The SHIFT operator

•  >> is shift right, << is shift left, operands are unsigned int and number of positions to shift

•  (1 << 3) is …000001 -> …0001000 (it’s 23) •  0xff00 is 0xff << 8, and 0xff is 0xff00 >> 8

!  Unsigned ints, be careful shifting signed integers (more later this semester)

•  0xAB & 0x0F = 0x0B •  0xAB & 0xF0 = 0xA0

•  0x0F and 0xF0 are called a bit mask

Page 21: Computer Science, Computer Architecture

21 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Sakai In Class Quiz 2.1

•  32-bit word with x,y and button fields !  bits 0-7 contain x position !  bits 8-15 contain y position !  bits 16-17 contain button (0 = left, 1 = middle, 2 = right) !  Bits 18-31 don’t matter

•  Which C Statements correctly set xpos, ypos & button?

button y x val = 01 1010 0011 0100 1100

A. xpos = val && 0x000ff; ypos = (val && 0x0ff00) >> 8; button = (val && 0x30000) >> 16;

B. xpos = val & 0x000ff; ypos = (val & 0x0ff00) >> 8; button = (val & 0x30000) >> 16;

C. xpos = val & 0x000ff; ypos = (val & 0x0ff00) << 8; button = (val & 0x30000) << 16;

D. xpos = val & 0x000ff; ypos = val & 0x0ff00 >> 1; button = val & 0x30000 >> 2;

Page 22: Computer Science, Computer Architecture

22 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Sakai In Class Quiz 2.1: Answer

•  32-bit word with x,y and button fields !  bits 0-7 contain x position !  bits 8-15 contain y position !  bits 16-17 contain button (0 = left, 1 = middle, 2 = right) !  Bits 18-31 don’t matter

•  Which C Statements correctly set xpos, ypos & button?

button y x val = 01 1010 0011 0100 1100

A. xpos = val && 0x000ff; ypos = (val && 0x0ff00) >> 8; button = (val && 0x30000) >> 16;

Logical AND

B. xpos = val & 0x000ff; ypos = (val & 0x0ff00) >> 8; button = (val & 0x30000) >> 16;

C. xpos = val & 0x000ff; ypos = (val & 0x0ff00) << 8; button = (val & 0x30000) << 16; Shift wrong direction; value not in least significant bits

D. xpos = val & 0x000ff; ypos = val & 0x0ff00 >> 1; button = val & 0x30000 >> 2; Precedence…shifts mask first; shift amount wrong

Page 23: Computer Science, Computer Architecture

23 © Alvin R. Lebeck From Sorin, Hilton, Roth

Functions

•  Encapsulate computation !  Reuse or clarity of code !  Cannot define functions within functions

•  Must be declared before use! int div2(int x,int y); /* declaration here */ main() {

int a; a = div2(10,2);

} int div2(int x, int y) { /* implementation here */

return (x/y); }

•  Or put functions at top of file (doesn’t always work)

Compsci / ECE 250

Page 24: Computer Science, Computer Architecture

24 © Alvin R. Lebeck From Sorin, Hilton, Roth

Global Variables

•  Global variables: Accessible from any function #include <stdio.h> float f = 0; void bar () { f = 0.5; } int main() { f =0.31234; bar(); printf(“The value is %f \n”, f); } Output is: The value is 0.5

Compsci / ECE 250

Page 25: Computer Science, Computer Architecture

25 © Alvin R. Lebeck From Sorin, Hilton, Roth

Memory Partitions

•  Text for instructions !  add res, src1, src2 !  mem[res] = mem[src1] +

mem[src2]

•  Data !  static (constants, global variables) !  dynamic (heap, malloc / new

allocated) !  grows up

•  Stack !  local variables !  grows down

•  Variables are names for memory locations !  int x;

Stack

Data

Text Reserved 0

2n-1

Typical Address Space

Heap

Compsci / ECE 250

Page 26: Computer Science, Computer Architecture

26 © Alvin R. Lebeck From Sorin, Hilton, Roth

A Simple Program’s Memory Layout

... int result; // global var int main() { int x; ... result = x + result; ...

} For now, think of this as performing: mem[0x208] = mem[0x400] + mem[0x208]

Stack

Text

Data

Reserved 0

2n-1

Heap

x 0x400 5

result 0x208 3

Compsci / ECE 250

Page 27: Computer Science, Computer Architecture

27 © Alvin R. Lebeck From Sorin, Hilton, Roth

Sakai In Class Quiz 2.2

#include <stdio.h> int a = 0; float f = 0.5; void setvals() { float f = 0.5; a = 78; } int main() { int a = 23; f =0.31234; setvals(); printf(“The values are %d, %f \n”,a,f); }

•  What is the result? a)  a = 78, f = 0.5 b)  a = 78, f = 0.31234 c)  a = 23, f = 0.5 d)  a = 23, f = 0.31234

Compsci / ECE 250

Page 28: Computer Science, Computer Architecture

28 © Alvin R. Lebeck From Sorin, Hilton, Roth

Sakai In Class Quiz 2.2

#include <stdio.h> int a = 0; float f = 0.5; void setvals() { float f = 0.5; a = 78; } int main() { int a = 23; f =0.31234; setvals(); printf(“The values are %d, %f \n”,a,f); }

Compsci / ECE 250

Stack

Text

Data

Reserved 0

2n-1

Heap

a 0xF0020 f 0x F0000

f 0x20004 a 0x 20000

Page 29: Computer Science, Computer Architecture

29 © Alvin R. Lebeck From Sorin, Hilton, Roth

Reference vs. Pointer

Java !  “The value of a reference type variable, in contrast to that of a

primitive type, is a reference to (an address of) the value or set of values represented by the variable” http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

!  Cannot manipulate the value of the reference

C !  A pointer is a variable that contains the location of another

variable !  A pointer is a memory location that contains the address of

another memory location !  Can manipulate the value of pointer (double edge sword)

Compsci / ECE 250

Page 30: Computer Science, Computer Architecture

30 © Alvin R. Lebeck From Sorin, Hilton, Roth

Pointers

•  Declaration of pointer variables !  int *x_ptr; char *c_ptr; void *ptr;

•  How do we get the location (address) of a variable? Use one of the following: 1.  Use the & ‘address of’ operator

!  x_ptr = &intvar; 2.  From another pointer (yes we can do arithmetic on them)

!  x_ptr = y_ptr + 18; 3.  Return from memory allocator

!  x_ptr = (int *) malloc(sizeof(int)); !  Similar to java new, but must explicitly free memory (i.e., free(x_ptr));

Compsci / ECE 250

Page 31: Computer Science, Computer Architecture

31 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Pointers

•  �address of� operator & !  don�t confuse with bitwise AND operator

Given int x; int* p; // p points to an int p = &x;

Then *p = 2; and x = 2; produce the same result

Note: p is a pointer, *p is an int

•  What happens for p = 2?;

0x26cf0

x 0x26cf0

p 0x26d00 ... On 32-bit machine, p is 32-bits

Page 32: Computer Science, Computer Architecture

32 © Alvin R. Lebeck From Sorin, Hilton, Roth

Pointers

•  De-reference using *ptr to get what is pointed at

Compsci / ECE 250

statement x x_ptr int x; ?? ?? int *x_ptr; ?? ?? x = 2 2 ?? x_ptr = &x; 2 &x *x_ptr = 68; 68 &x x_ptr = 200; 68 200 *x_ptr = 42 68 200

•  Be careful with assignment to a pointer variable !  You can make it point anywhere…can be very bad !  You will, this semester, likely experience a “segmentation fault” !  What is 200?

Page 33: Computer Science, Computer Architecture

33 © Alvin R. Lebeck From Sorin, Hilton, Roth

Sakai In Class Quiz 2.3 Which Version Correctly Swaps Values?

void swap (int x, int y){

int temp = x;

x = y;

y = temp;

}

main() {

int a = 3;

int b = 4;

swap(a, b);

printf(“a = %d, b= %d\n”, a, b);

}

A.

void swap (int *x, int *y){

int temp = *x;

*x = *y;

*y = temp;

}

main() {

int a = 3;

int b = 4;

swap(&a, &b);

printf(“a = %d, b= %d\n”, a, b);

}

B.

Compsci / ECE 250

Page 34: Computer Science, Computer Architecture

34 © Alvin R. Lebeck From Sorin, Hilton, Roth Compsci / ECE 250

Strings as Arrays

•  A string is an array of characters with �\0� at the end •  Each element is one byte, ASCII code •  �\0� is null (ASCII code 0) •  char str1[256] is similar to str2 = (char *) malloc(256);

0 1 43 15 s t �\0� r i g

16 42

Page 35: Computer Science, Computer Architecture

35 © Alvin R. Lebeck From Sorin, Hilton, Roth

Structures

•  Loosely like objects !  Have member variables !  Do not have methods!

•  Structure definition with struct keyword struct student_record {

int id; float grade;

} rec1, rec2;

•  Declare a variable of the structure type with struct keyword struct student_record onerec, *tworec;

•  Access the structure member fields with !  ‘.’ structvar.member (e.g., onerec.id = 12;) !  ‘->’ structprt->member (e.g., tworec->id;)

Compsci / ECE 250

Page 36: Computer Science, Computer Architecture

36 © Alvin R. Lebeck From Sorin, Hilton, Roth

Summary

•  C is different from Java !  Procedural !  Structures not objects… !  Pointers!

•  Next time !  Explicit memory deallocation !  Pointer manipulation !  Linked Structures

Compsci / ECE 250