CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf ·...

41
CSC 2400: Computing Systems Professor Mirela Damian http://www.csc.villanova.edu/~mdamian/ 1 Introductions • Mirela Damian (professor) Room 167A in the Mendel Science Building Room 167A in the Mendel Science Building [email protected] Rusul Alsalihi (teaching assistant) Rusul Alsalihi (teaching assistant) Room 159 in the Mendel Science Building • ralsalih@villanova.edu • Programming assistants Room 292 in the Mendel Science Building Room 292 in the Mendel Science Building 2

Transcript of CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf ·...

Page 1: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

CSC 2400: Computing Systems

Professor Mirela Damian

http://www.csc.villanova.edu/~mdamian/

1

Introductions

• Mirela Damian (professor)• Room 167A in the Mendel Science BuildingRoom 167A in the Mendel Science Building• [email protected]

• Rusul Alsalihi (teaching assistant)• Rusul Alsalihi (teaching assistant)• Room 159 in the Mendel Science Building• [email protected]@

• Programming assistants• Room 292 in the Mendel Science BuildingRoom 292 in the Mendel Science Building

2

Page 2: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

What do Computers Do?p

• Do a survey on campus“ ”

Computers Execute Instructions

• Numerous “correct” answers

Computers Execute Instructions.

That’s all!

3

What Kind of Instructions?

• Strictly speaking, computers only understand hi l (bi hi d )machine language (binary machine code).

4

Page 3: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Hierarchy of Computer Languages

• “Click” an icon• Press a key• Verbal command

Human interface languages

• SGML / XMLMark‐up languages

•Oracle / SQL• MS Access Database languages

• Lisp / ML • Shells / scripts• Python Interpreted languages

• HTML Mark‐up languages

• Pascal/Fortran

Python• Basic / V‐Basic• Java

Interpreted languages

• Assembly Lo le el lang ages

• ADA• C++ • C

High‐level compiled languages

5

Assembly• Machine Code

Low‐level languages

Course Goals: “Look under the hood”

• “Help you learn what happens “under the hood” of computer systemsunder the hood of computer systems

• Specifically, two downward toursLanguage levels tour• Language levels tour• High-level language (C) → assembly language →

machine language (IA-32)g g ( )• Service levels tour

• High-level language (C) → standard libraries → operating system (Linux)operating system (Linux)

• Reveal how abstractions are created

6

Page 4: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Course Goals: Why C?y

• Q: Why C instead of Java?

• A: C facilitates language levels tour• C is a lower-level language• C is closely related to assembly language• C is closely related to assembly language

• A: C facilitates service levels tourLi i itt i C• Linux is written in C

7

Course Goals: Why Linux?y

• Q: Why Linux instead of Microsoft Windows?

• A: Linux is good for education and research• Linux is open-source and well-specified

• A: Linux is good for programming• Linux is a variant of Unix

U i h GNU i h i• Unix has GNU, a rich open-source programming environment

8

Page 5: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Course Goals: Summaryy

• Help you to become a...

9

Power Programmer!!!

Resources: Books

• Textbook• System Programming with C and Unix Adam HooverSystem Programming with C and Unix, Adam Hoover.

• Covers both language-level and system-level tours• Some topics will be covered in more depth in class

• Lectures based on textbook and online material • The textbook is mandatoryy• Homework assignments are based on textbook and in

class lectures.All homework due at start of class; not at the end of• All homework due at start of class; not at the end of class.

• Additional materials posted on the class web site

10

• Additional materials posted on the class web site.

Page 6: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Resources: Programming Environment

• One Linux machine named felix.

Any lab, or your own PC/MAC/Linux computer.

felix.csc.villanova.edu

SSH

LinuxLinux

GNU

YourYourPgm

felix

11

Resources: Programming Environment

• Several Unix machines: degas, cezanne, tanner, picasso, rodin, cassatt, gauguin, matisse.

Any lab, or your own PC/Mac/Linux Computer

p , , , g g ,

tanner.csc.villanova.edu

SSHUnixUnix

GNU

YourYourPgm

tanner

12

rodin

matisse

Page 7: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Try to Log In Now

• Locate and invoke Secure Shell Client from the Start menu• Click on the ‘Quick Connect’ tab • In the ‘Host Name’ textbox, type in

tanner.csc.villanova.edu

• In the ‘User Name’ textbox, type in your username (the one the system administrator emailed you)

• Click on ‘Connect’• A text window with the shell prompt will be opened for you.• This is a command line interface. • You will interact with the Unix operating system by typing in• You will interact with the Unix operating system by typing in

commands at the shell prompt.Try for example hostname

13

The name of the machine (tanner) will be displayed.

Workload Distribution

• To use our Unix resources efficiently, from tanner connect arbitrarily to rodin or degas by typing in eithery g y yp g

ssh rodin

ssh degas

T t d t ki hi• Too many students working on one same machine can slow it down considerably.

• To log off, simply type in

exit

14

exit

Page 8: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Gradingg

• Assignments (45%)• Pencil and paperp p• Clean, readable, working code• On time (no late submission)• First assignment is available now• First assignment is available now

• Exams (45%)• Midterm• Midterm• Comprehensive final exam

• Class Participation (10%)Class Participation (10%)

• No makeup assignments or exams

15

• Lecture attendance is mandatory

Programming Assignmentsg g g

• Start early to allow time for debugging.

16

Page 9: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Course Schedule• Very generally…

Weeks Lectures

1-2 Introduction to C and Unix

3 7 Advanced C3-7 Advanced C

7 Midterm exam

Recess

8-11 “Under the hood” – assembly language

Thanksgiving Recess

12-15 “Under the hood” – Unix processes

Dec. 19 Final exam, 6:00 – 8:30 pm

17

• See course web site for details

An q estions before e start?Any questions before we start?

18

Page 10: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Design Goalsg

• Java design goals• Support object-oriented programmingpp j p g g• Allow same program to be executed on multiple operating systems• Support using computer networks• Execute code from remote sources securelyy• Adopt the good parts of other languages (esp. C and C++)

• Implications for Java• Good for application-level programming• High-level

• Virtual machine insulates programmer from underlying assembly language, machine language, hardware

• Portability over efficiency• Security over efficiency

19

• Security over flexibility

C vs. Java: Design Goalsg

• C design goals• Support structured programmingpp p g g• Support development of the Unix OS and Unix tools

• As Unix became popular, so did C

I li ti f C• Implications for C• Good for system-level programming

• But often used for application-level programming – sometimes inappropriately

• Low-level• Close to assembly language; close to machine language; close to

hardware• Efficiency over portability• Efficiency over security

20

• Flexibility over security

Page 11: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Design Goalsg

Differences in design goals explain many differences• Differences in design goals explain many differences between the languages

• C’s design goal explains many of its eccentricities• C s design goal explains many of its eccentricities

We’ll see examples throughout the course• We’ll see examples throughout the course

21

C vs. Java: Overview

• Dennis Ritchie on the nature of C:

• “C has always appealed to systems programmers who like the terse, concise manner in which powerful expressions can be coded.”

• “C allowed programmers to (while sacrificing portability) have directC allowed programmers to (while sacrificing portability) have direct access to many machine-level features that would otherwise require the use of assembly language.”

• “C is quirky, flawed, and an enormous success. While accidents of q y, ,history surely helped, it evidently satisfied a need for a system implementation language efficient enough to displace assembly language, yet sufficiently abstract and fluent to describe algorithms

22

and interactions in a wide variety of environments.”

Page 12: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Overview (cont.)( )

• Bad things you can do in C that you can’t do in Java• Bad things you can do in C that you can t do in Java• Shoot yourself in the foot (safety)• Shoot others in the foot (security)• Ignore wounds (error handling)• Ignore wounds (error handling)

• Dangerous things you must do in C that you don’t in Java• Explicitly manage memory via malloc() and free()Explicitly manage memory via malloc() and free()

• Good things you can do in C, but (more or less) must do in Java• Program using the objected-oriented style

• Good things that you can’t do in C but can do in Java

23

• Write completely portable code

C vs. Java: Details

Remaining slides provide some details• Remaining slides provide some details• Suggestion: Use for future reference

Slid d b i fl• Slides covered briefly now …

24

Page 13: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Details (cont.)( )

Java C

H ll j h ll

OverallProgram

Hello.java:

public class Hello {public static voidmain(String[] args) {System out println(

hello.c:

#include <stdio.h>

int main(void) {printf("Hello world\n");

Structure System.out.println("Hello, world");

}}

printf( Hello, world\n );return 0;

}

Building

% javac Hello.java% lsHello.classHello.java%

% gcc hello.c% lsa.outhello.c%

Running% java HelloHello, world%

% ./a.outHello, world%

25

C vs. Java: Details (cont.)( )

Java C

Character type char // 16-bit unicode char /* 8 bits */

Integral types

byte // 8 bitsshort // 16 bits

(unsigned) char(unsigned) short

Integral types int // 32 bitslong // 64 bits

(unsigned) int(unsigned) long

Floating point float // 32 bitsfloatdoubleg p

types double // 64 bitsdoublelong double

Logical type boolean/* no equivalent *//* use integral type */g yp

Generic pointer type

// no equivalent void*

#define MAX 1000

26

Constants final int MAX = 1000;#const int MAX = 1000;enum {MAX = 1000};

Page 14: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Details (cont.)( )

Java C

Arraysint [] a = new int [10];float [][] b =

new float [5][20];

int a[10];float b[5][20];

Array bound checking

// run-time check /* no run-time check */

Pointer type// Object reference is an// implicit pointer

int *p;// implicit pointer

Record type

class Mine {int x;float y;

struct Mine {int x;float y;

} }

27

C vs. Java: Details (cont.)( )

Java C

StringsString s1 = "Hello";String s2 = new

String("hello");

char *s1 = "Hello";char s2[6];strcpy(s2, "hello");

String concatenation

s1 + s2s1 += s2

#include <string.h>strcat(s1, s2);

Logical ops &&, ||, ! &&, ||, !

! !Relational ops =, !=, >, <, >=, <= =, !=, >, <, >=, <=

Arithmetic ops

+, -, *, /, %, unary - +, -, *, /, %, unary -

Bit i | ^ | ^Bitwise ops >>, <<, >>>, &, |, ^ >>, <<, &, |, ^

Assignment ops

=, *=, /=, +=, -=, <<=, >>=, >>>=, =, ^=, |=, %=

=, *=, /=, +=, -=, <<=, >>=, =, ^=, |=, %=

28

Page 15: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Details (cont.)( )

Java C

if stmt

if (i < 0)statement1;

elsestatement2;

if (i < 0)statement1;

elsestatement2;

switch (i) {case 1:

...

switch (i) {case 1:

...

switch stmt

break; case 2:

...break;

break; case 2:

...break;

default:...

}

default:...

}

t t t // i l t S b l

29

goto stmt // no equivalent goto SomeLabel;

C vs. Java: Details (cont.)( )

Java C

for stmtfor (int i=0; i<10; i++)

statement;

int i;for (i=0; i<10; i++)

statement;

hile (i < 0) hile (i < 0)while stmt

while (i < 0)statement;

while (i < 0)statement;

d hil t t

do {statement;

do {statement;

do-while stmt;

…} while (i < 0)

;…

} while (i < 0)

continue stmt continue; continue;

labeled continue stmt

continue SomeLabel; /* no equivalent */

break stmt break; break;

30

labeled breakstmt

break SomeLabel; /* no equivalent */

Page 16: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

C vs. Java: Details (cont.)( )

Java C

return stmtreturn 5;return;

return 5;return;

{ {Compound stmt(alias block)

statement1;statement2;

}

statement1;statement2;

}

Exceptions throw, try-catch-finally /* no equivalent */

Comments/* comment */// another kind

/* comment */

// another kind

Method / function call

f(x, y, z);someObject.f(x, y, z);SomeClass f(x y z);

f(x, y, z);

31

SomeClass.f(x, y, z);

Example C Programp g

• File circle.c:#include <stdio.h>

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

{int radius;int diam;double circum;double circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = 3 14159 * (double)diam;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

32

return 0;}

Page 17: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Building and Runningg g

• To build (preprocess, compile, assemble, and link):$ gcc circle.c –o circle

• To run:

$ gcc circle.c o circle

$ / i l$ ./circle

Enter the circle's radius:

5Typed byuser

A circle with radius 5 has diameter 10

and circumference 31.415900.

33

Steps in the Build Processp• To build one step at a time:

$ gcc –E circle.c > circle.i

Preprocess:circle.c → circle.i

Compile:$ gcc –S circle.i

$ gcc –c circle.s

$ gcc circle.o –o circle

Compile:circle.i → circle.s

Assemble:circle.s → circle.o

Link:circle o → circle

• Why build one step at a time?• Helpful for learning how to interpret error messages

circle.o → circle

34

• Helpful for learning how to interpret error messages• Permits partial builds (described later in course)

Page 18: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

The Preprocessor’s View

• File circle.c:

p

#include <stdio.h>

Preprocessor directivePreprocessor replaces with contents#

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

of file /usr/include/stdio.h

{int radius;int diam;double circum;printf("Enter the circle's radius:\n");

Commentprintf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

Preprocessor removes

radius, diam);printf("and circumference %f.\n", circum);return 0;

}

35

Results of Preprocessing

• File circle.i:

p g

int printf(char* );Declarations of printf(), scanf(),

int printf(char*, …);int scanf(char*, …);…

int main(void){

and other functions; compiler willhave enough information to check subsequent function calls

{int radius;int diam;double circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);radius, diam);printf("and circumference %f.\n", circum);return 0;

}

36

Where are the DEFINITIONS of printf() and scanf() ?

Page 19: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

What is Wrong?g

#include <stdio.h>

int SomeFunction(x);

int main(){{

int result;

result = SomeFunction(5);

ret rn 0return 0;}

int SomeFunction(int x){

return x * x;}

37

The Compiler’s View

• File circle.i:

p

int printf(char*, …);

Function declarationsCompiler notes return typesp ( , );

int scanf(char*, …);…

int main(void){

Compiler notes return typesand parameter types so it cancheck your function calls

{int radius;int diam;double circum;printf("Enter the circle's radius:\n");scanf("%d" &radius);

Functionscanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);

definition

Compoundprintf("and circumference %f.\n", circum);return 0;

}

Compoundstatementalias block

38

Return type of main()should be int

Page 20: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

The Compiler’s View (cont.)

• File circle.i:

p ( )

int printf(char*, …);Declaration statementsM t b f th

p ( , );int scanf(char*, …);…

int main(void){

Must appear before any otherkind of statement in block;variables must be declaredbefore use{

int radius;int diam;double circum;printf("Enter the circle's radius:\n");scanf("%d" &radius);

before use

Function callscanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);

statements

printf("and circumference %f.\n", circum);return 0;

}

& (“address of”) operator

39

String constants Explained later in course,with pointers

What is Wrong?g

#include <stdio.h>

int main(){

int sum;

int i;;

for(int i = 1; i <= 10; i++)sum = sum + i;

int factint fact;

for(i = 1; i <= 10; i++)fact = fact * i;

return 0;}

40

Page 21: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

The Compiler’s View (cont.)

• File circle.i:

p ( )

int printf(char*, …);p ( , );int scanf(char*, …);…

int main(void){ Constant of type double

Constant of type int

{int radius;int diam;double circum;printf("Enter the circle's radius:\n");scanf("%d" &radius);

Expressionstatements

yp

scanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);

statements

printf("and circumference %f.\n", circum);return 0;

}

Cast operatorUnnecessary here, but good style to avoid

41

mixed-type expressions

The Compiler’s View (cont.)

• File circle.i:

p ( )

int printf(char*, …);p ( , );int scanf(char*, …);…

int main(void){

Function call statementsprintf() can be called with1 l

{int radius;int diam;double circum;printf("Enter the circle's radius:\n");scanf("%d" &radius);

1 or more actual parameters

scanf("%d", &radius);diam = 2 * radius;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

} Return statementConvention: 0 returned from

42

main() means success; non-0means failure

Page 22: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Results of Compiling

• File circle.s:

p g

.section .rodata.LC0:

.string "Enter the circle's radius:\n".LC1:

.string "%d"

Assembly language

….section .text.globl main.type main, @function

main:pushl %ebpp pmovl %esp, %ebp…pushl $.LC0call printfaddl $16, %espsubl $8, %espleal -4(%ebp), %eaxpushl %eaxpushl $.LC1call scanf

43• Still missing definitions of printf() and scanf()

The Assembler’s View• File circle.s:

.section .rodataLC0.LC0:

.string "Enter the circle's radius:\n".LC1:

.string "%d"…

.section .text.section .text

.globl main

.type main, @functionmain:

pushl %ebpmovl %esp, %ebp

Assembly language

…pushl $.LC0call printfaddl $16, %espsubl $8, %espleal 4(%ebp) %ealeal -4(%ebp), %eaxpushl %eaxpushl $.LC1call scanf

44

• Assembler translates assembly language into machine language• Details provided in 2nd half of course

Page 23: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Results of Assembling

• File circle.o:

g

Machine languageListing omitted

Not human-readable

• Object file

• Still missing definitions of printf() and scanf()

45

The Linker’s View

• File circle.o:

Machine languageListing omitted

Not human-readable

• The linker:• Observes that

• Code in circle.o calls printf() and scanf()• Code in circle.o does not define printf() or scanf()

• Fetches machine language definitions of printf() and scanf() from standard C library (/usr/lib/libc.a on your machine)

• Merges those definitions with circle.o to create…

46

Page 24: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Results of Linking

• File circle:

g

Listing omitted

Not human-readableMachine language

• Complete executable binary file

1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1

1 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1

1 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0

1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1

1 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1

47

1 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1

Run-Time View

• At run-time, memory devoted to program is divided into sections:

TEXT

RODATA

• TEXT (read-only)• Stores machine language instructionsRODATA

DATA

BSS

HEAP

Stores _____________________

• RODATA (read-only)St

machine language instructions

read only data (esp strings)HEAP • Stores _____________________

• STACK (read/write)

read-only data (esp. strings)

• Stores _____________________

• Other sections described later in course

local variables

48

STACK

Other sections described later in course

Page 25: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Run-Time View: Startupp

• At program startup:RODATA contains

t i t t dSTACK iTEXT contains every string constant used in program; each is an arrayof characters, terminated withthe null character (‘\0’)

STACK isempty

TEXT containsmachine languagecode defining main(),printf() scanf() etc

TEXT STACK RODATA

E h i l ’ di \ \0

the null character ( \0 )printf(), scanf(), etc.

Enter the circle’s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0

---

printf

scanf

49

---

Run-Time View: Declarations

int radius;int diam;double circum; C t ll tdouble circum; Computer allocates memory

onto STACK for each local variable:4 bytes for int, 8 bytes for double

TEXT STACK RODATA

Enter the circle’s radius\n\0Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0

circum---

printf

scanf

50radiusdiam---

Page 26: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Run-Time View: Writing a Stringg g

printf("Enter the circle's radius:\n");

Computer passes address containingComputer passes address containing‘E’ to printf(); printf() prints charactersuntil it encounters ‘\0’

TEXT STACK RODATA

Enter the circle’s radius\n\0Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0

circum---

printf

scanf

51radiusdiam---

Run-Time View: Reading an intg

scanf("%d", &radius);

Computer passes addressComputer passes address containing ‘%’ to scanf(). scanf() waits for user input; user types 5;

scanf() reads character(s), converts to decimal (d) constant assigns to radius

TEXT STACK RODATA

Enter the circle’s radius\n\0

decimal (d) constant, assigns to radius

Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0

circum---

printf

scanf

52radiusdiam---

5

Page 27: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Run-Time View: Computing Resultsp g

diam = 2 * radius;circum = 3.14159 * (double)diam;

Computer uses radiusComputer uses radiusto compute diam and circum

TEXT STACK RODATA

Enter the circle’s radius\n\0Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0 31.4159circum

---

printf

scanf

535

10

radiusdiam---

Run-Time View: Writing an intgprintf("A circle with radius %d has diameter %d\n",

radius, diam);Computer passes address of ‘A’, valuef di d l f di t i tf()of radius, and value of diam to printf().

printf() prints until ‘\0’, replacing 1st %d with character comprising 5, 2nd %d with characters comprising 10

TEXT STACK RODATA

Enter the circle’s radius\n\0

characters comprising 10

Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0 31.4159circum

---

printf

scanf

545

10

radiusdiam---

Page 28: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Run-Time View: Writing a doublegprintf("and circumference %f.\n", circum);

Computer passes address of ‘a’ and value of circum to printf(). printf() prints until ‘\0’, replacing %f with characters comprising 31.415900

TEXT STACK RODATA

Enter the circle’s radius\n\0Enter the circle s radius\n\0

%d\0

A circle with radius %d has diameter %d\n\0

------

mainA circle with radius %d has diameter %d\n\0

and circumference %f.\n\0 31.4159circum

---

printf

scanf

555

10

radiusdiam---

Run-Time View: Exitingg

return 0;

Computer reclaims memory usedby program; sections cease to exist

56

Page 29: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

What Goes Where?

int fact(n){

int i, result=1;

for(i = 1; i<=n; i++)result = result * i;

return result;}

int main(){{

int n;

printf(“Enter a value\n”);scanf(“%d”, &n);printf(“The factorial of %d is %d”, n, fact(n));return 0;

}

57

What Goes Where?int fact(n){

int i, ret=1;

int main(){

int n;for(i = 1; i<=n; i++)ret = ret * i;

return ret;}

printf(“Enter a value\n”);scanf(“%d”, &n);printf(“The factorial of %d is %d”, n,fact(n));return 0;

}

TEXT STACK RODATA

}

58

Page 30: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

“Circle” Programg

• File circle.c:#include <stdio.h>

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

{int radius;int diam;double circum;double circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = 3 14159 * (double)diam;circum = 3.14159 * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

59

return 0;}

Toward Version 2

Problem (stylistic flaw):• Problem (stylistic flaw):• 3.14159 is a “magic number”• Should give it a symbolic name to

• Increase code clarity• Thereby increase code maintainability

• Solution:• Solution:• (In Java: final fields, final variables)• In C: three approaches…

60

Page 31: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Symbolic Constants: #definey

• Approach 1: #definePreprocessor directive:

void f(void) {#define START STATE 0

replace START_STATE with 0

_#define POSSIBLE_COMMENT_STATE 1#define COMMENT_STATE 2...int state; Preprocessorint state;...state = START_STATE;...

Preprocessorreplaceswith 0

state = COMMENT_STATE;...

}Preprocessorreplaceswith 2

61

with 2

Symbolic Constants: #definey

• Approach 1 strengths• Preprocessor does substitutions only for tokensp y

• Preprocessor does not do substitutions within string constants

int mySTART_STATE; /* No replacement */

p g

• Simple textual replacement; works for any type of data

printf("What is the START_STATE?\n"); /* No replacement */

Simple textual replacement; works for any type of data

#define PI 3.14159

62

Page 32: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Version 2 using #defineg

#include <stdio.h>

#define PI 3.14159

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

{int radius;int diam;d bl idouble circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = * (double)diam;PI____________ ( ) ;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

}

63

}

Symbolic Constants: #define

• Approach 1 weaknesses

y

• Preprocessor does not• Preprocessor does not

void f(void) {#define MAX 1000

void f(void) {#

Preprocessor does notrespect scope

Preprocessor does notrespect context

#define MAX 1000…

}void g(void) {{

#define MAX 1000…int MAX = 2000;

}{

int MAX = 2000;…

}

Preprocessorreplaceswith 1000 !!!with 1000 !!!

• Conventions:• Use all uppercase for constants -- and only for constants

64

Use all uppercase for constants -- and only for constants• Place #defines at beginning of file, not within function definitions

Page 33: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Symbolic Constants: consty

• Approach 2: “constant variables” (oxymoron!!!)

void f(void){

const int START_STATE = 0;const int POSSIBLE COMMENT STATE = 1;const int POSSIBLE_COMMENT_STATE 1;const int COMMENT_STATE = 2;......i t t t

Compiler does notint state;...state = START_STATE;...

allow value ofSTART_STATEto change

state = COMMENT_STATE;...

}

65

Version 2 using constg

#include <stdio.h>

const double PI = 3.14159;

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

{int radius;int diam;d bl idouble circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = * (double)diam;PI____________ ( ) ;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

}

66

}

Page 34: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Symbolic Constants: consty

• Approach 2 strengths• Works for any type of datay yp

• Handled by compiler, not preprocessor; compiler respects context

const double PI = 3.14159;

y p , p p ; p pand scope

• Approach 2 weaknesses• Does not work for array lengths (unlike C++)

const int ARRAY_LENGTH = 10;...

/ /int a[ARRAY_LENGTH]; /* Compiletime error */

67

Symbolic Constants: enumy

• Approach 3: EnumerationsDefines a new

void f(void)

Defines a newtype named“enum State”

{enum State {START_STATE, POSSIBLE_COMMENT_STATE,

COMMENT_STATE, ...};

enum State state;Th f

enum State state;...state = START_STATE;...state = COMMENT_STATE;

The constants of type“enum State” areSTART_STATE, …

...} Defines a variable

named “state”to be of type

68

to be of type“enum State”

Page 35: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Symbolic Constants: enumy

Approach 3 note• Approach 3 note• Enumerated constants are interchangeable with ints

• START_STATE is the same as 0• POSSIBLE_COMMENT_STATE is the same as 1• Etc.

state = 0; /* Can assign int to enum. */i = START_STATE; /* Can assign enum to int. */

69

Symbolic Constants: enumy

• Approach 3 strengths• Can explicitly specify values for namesp y p y

enum State {START_STATE = 5, POSSIBLE_COMMENT_STATE = 3, COMMENT_STATE = 4, ...};

• Can omit type name, thus effectively giving names to int literals

enum {MAX_VALUE = 9999};...

• Works when specifying array lengths

int i = MAX_VALUE;

{ARRAY LENGTH 10}enum {ARRAY_LENGTH = 10};...int a[ARRAY_LENGTH];...

70

Page 36: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Symbolic Constants: enumy

Approach 3 weakness• Approach 3 weakness• Does not work for non-integral data types

enum {PI = 3.14159}; /* Compiletime error */

71

Symbolic Constant Style Rulesy y

• In summary of symbolic constants…

Style rules:• Style rules:

1 Use enumerations to give symbolic names1. Use enumerations to give symbolic namesto integral constants

2 Use const variables to give symbolic names2. Use const variables to give symbolic names to non-integral constants

3 Use #define with all uppercase at beginning of file3. Use #define with all uppercase at beginning of file

72

Page 37: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

“Circle” Program (Version 2)

• File circle.c (version 2):

g ( )

#include <stdio.h>#

int main(void)

/* Read a circle's radius from stdin, and compute and write itsdiameter and circumference to stdout. Return 0. */

{const double PI = 3.14159;int radius;int diam;double circum;double circum;printf("Enter the circle's radius:\n");scanf("%d", &radius);diam = 2 * radius;circum = PI * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius, diam);printf("and circumference %f.\n", circum);return 0;

}

73

}

Toward Version 3

Problem:• Problem:• Program does not handle bad user input

$ circle

Enter the circle's radius:

abcabc

User enters a non-number.How can the program detect that?How can the program detect that?What should the program do?

74

Page 38: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

scanf

75

Detecting Bad User Inputg p

• Solution Part 1: Detecting bad user input• scanf() returns number of values successfully read() y• Example:

int returnValue;…

t V l f("%d" &i)

• Or, more succinctly:

returnValue = scanf("%d", &i);if (returnValue != 1)

/* Error */

Or, more succinctly:…if (scanf("%d", &i) != 1)

/* Error */

• Or, for more than one variable:…if (scanf("%d%d", &i, &j) != 2)

76

j/* Error */

Page 39: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Reporting Failure to Userp g

• Solution Part 2: Reporting failure to the user

Stream Default Binding

Purpose C Functions

stdin Keyboard “Normal” input scanf( );stdin Keyboard Normal input scanf(…);fscanf(stdin, …);

stdout Video screen

“Normal” output printf(…);fprintf(stdout );screen fprintf(stdout, …);

stderr Video screen

“Abnormal” outputfprintf(stderr, …);

• To report failure to user, should write a message to stderr

77

Reporting Failure to OSp g

• Solution Part 3: Reporting failure to the operating system

Nature of Program Status Code that ProgramNature of Program Completion

Status Code that ProgramShould Return to OS

Successful 0EXIT SUCCESS (#defined in stdlib h as 0)

To generate status code x program should:

EXIT_SUCCESS (#defined in stdlib.h as 0)

Unsuccessful EXIT_FAILURE (#defined in stdlib.h as ???)

• To generate status code x, program should:• Execute return x statement to return from main() function, or• Call exit(x) to abort program

System-dependent;• Shell can examine status code

• Note:• In main() function, return statement and exit() function have same effect

System dependent;on tanner, 1

78

() , ()• In other functions, they have different effects

Page 40: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

“Circle” Program (Version 3)g ( )#include <stdio.h>

#include <stdlib.h>

int main(void)/* Read a circle's radius from stdin, and compute and write its

diameter and circumference to stdout. Return 0 if successful. */{{

const double PI = 3.14159;int radius;int diam;double circum;printf("Enter the circle's radius:\n");printf("Enter the circle's radius:\n"); if (scanf("%d", &radius) != 1){

fprintf(stderr, "Error: Not a number\n");exit(EXIT_FAILURE); /* or: return EXIT_FAILURE; */

}diam = 2 * radius;circum = PI * (double)diam;printf("A circle with radius %d has diameter %d\n",

radius diam);

79

radius, diam);printf("and circumference %f.\n", circum);return 0;

}

Summaryy

• Simple C programs• Program structureg• Defining symbolic constants

• #define, constant variables, enumerations• Detecting and reporting failureg p g

• The stderr stream• The exit() function

F ti lit f th d• Functionality of the gcc command• Preprocessor, compiler, assembler, linker

• Memory layout of a Linux process• Memory layout of a Linux process• TEXT, RODATA, STACK sections• (More sections – DATA, BSS, HEAP – later in the course)

80

Page 41: CSC 2400: Computing Systems - Villanova Universitymdamian/Past/csc2400fa12/notes/01_Intro3.pdf · #include  int main(void) {printf ... case 1: ... switch stmt break;

Getting Startedg

Check out course web site now• Check out course web site now

http://www.csc.villanova.edu/~mdamian/CSC2400.html

E l ti i t• Explore your computing environment• Assignment posted on the website

• Reading• Required: Chapters 2, 6.1, 8.1-8.3 from the textbook

Optional: Chapter 1• Optional: Chapter 1

81