Lecture 2: C Programm

Similar documents
Lecture 3: C Programm

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

C'Programming' data'separate'from'methods/functions' Low'memory'overhead'compared'to'Java'

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

ECE 15B COMPUTER ORGANIZATION

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS61C : Machine Structures

CS61C : Machine Structures

CS 61c: Great Ideas in Computer Architecture

HW1 due Monday by 9:30am Assignment online, submission details to come

CS61C : Machine Structures

High Performance Computing Lecture 1. Matthew Jacob Indian Institute of Science

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

More C Pointer Dangers

CS61C : Machine Structures

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

Intermediate Programming, Spring 2017*

Lectures 5-6: Introduction to C

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

REFERENCES, POINTERS AND STRUCTS

Functions:"" Breaking"large"computing"tasks"to" smaller"ones"

Programming Studio #9 ECE 190

EL2310 Scientific Programming

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

A Fast Review of C Essentials Part I

IT 252 Computer Organization and Architecture Introduction to the C Programming Language

CSE 374 Programming Concepts & Tools

Class Information ANNOUCEMENTS

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C Arrays, Strings, More Pointers Instructor: Steven Ho

[0569] p 0318 garbage

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers and Arrays 1

Homework #3 CS2255 Fall 2012

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

First of all, it is a variable, just like other variables you studied

C Introduction. Comparison w/ Java, Memory Model, and Pointers

BLM2031 Structured Programming. Zeyneb KURT


CS Programming In C

Introduction to Scientific Computing and Problem Solving

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

Pointers. 10/5/07 Pointers 1

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

In Java we have the keyword null, which is the value of an uninitialized reference type

Instructor: Randy H. Katz hbp://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #4. Agenda

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

C++ for Java Programmers

Variation of Pointers

Kurt Schmidt. October 30, 2018

Introduction to Programming Using Java (98-388)

Understanding Pointers

PRINCIPLES OF OPERATING SYSTEMS

Arrays and Pointers in C. Alan L. Cox

Pointers in C/C++ 1 Memory Addresses 2

Lecture 03 Bits, Bytes and Data Types

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Lectures 5-6: Introduction to C

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CS240: Programming in C

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Dynamic memory allocation (malloc)

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Agenda. Address vs. Value Consider memory to be a single huge array. Review. Pointer Syntax. Pointers 9/9/12

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Procedural Programming & Fundamentals of Programming

Lecture 3: Instruction Set Architecture

Topics Introduction to Microprocessors

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

CS61C : Machine Structures

Recitation #11 Malloc Lab. November 7th, 2017

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

CS 61C: Great Ideas in Computer Architecture Introduction to C

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

A brief introduction to C programming for Java programmers

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Systems Programming and Computer Architecture ( )

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Programming refresher and intro to C programming

CS201 Some Important Definitions

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Lectures 13 & 14. memory management

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Intermediate Programming, Spring 2017*

o Code, executable, and process o Main memory vs. virtual memory

Transcription:

0 3 E CS 1 Lecture 2: C Programm ing

C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes Relatively fast Heap memory management manual Pointers to manipulate shared data 2

The C runtime environment 3

Steps in program translation Code Time Compile Time Run Time Program in C Helloworld.c Compiler Hardware Program: Text Hile stored on computers hard disk or some secondary storage Executable: Program in machine code +Data in binary 1000110001100010000000000000000 1000110011110010000000000000100 1010110011110010000000000000000 1010110001100010000000000000100

What does gcc do? % gcc hello.c 5

What does gcc do? % gcc hello.c hello.c gcc a.out 6

What does gcc do? % gcc hello.c Source Program in C hello.c gcc a.out #include <stdio.h> void func1(int a, char *b) { if(a > 0) { *b = a ; } } int main() {.. func1(); printf( \abc ); } 7

What does gcc do? % gcc hello.c Source Program in C Executable : Equivalent program in machine language hello.c #include <stdio.h> void func1(int a, char *b) { if(a > 0) { *b = a ; } } int main() {.. func1(); printf( \abc ); } gcc a.out 0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111! 8

What does gcc do? % gcc hello.c %./a.out (executable loaded in memory and processed) Also referred to as running the C program gcc hello.c Source : Program in C a.out Executable : Equivalent program in machine language 9

How is other code included? Include Header files (.h) that contain function declarations - the function interface The corresponding.c files contain the actual code hello.h hello.c void func1(int, char *); int func2(char *, char *); #include <stdio.h> void func1(int a, char *b) { if(a > 0) { *b = a ; } } int main() {.. func1(); printf( \abc ); } 10

Manipulating data objects in C 11

How we manipulate variables depends on their data- type Data- types Basic: int, char, Hloat Derived: Pointers Arrays Structures enumerations 12

In C, a variable is declared by A. using it in an arithmetic expression B. preceding it with one or more keywords to indicate its data type, e.g. char c; C. initializing it to a value 13

Basic data object in memory A region in memory that contains a value and is associated with a name/identihier 102 20 num 4 bytes 14

Basic data object in memory A region in memory that contains a value and is associated with a name/identihier Attributes of a Data- object/variable: - Name/identiHier - Value - Address: Location in memory - Size - A unique data- type - Lifetime - Scope 102 20 num 4 bytes 15

Declarations and dehinitions char c= a ; /* 1 byte */ short s; /* 2 bytes */ int a; /* usually 4 bytes - signed */ unsigned int a=0; /* usually 4 bytes*/ float f; /* usually 4 bytes use sizeof(hloat)*/ 16

A. Yes Can we change the location of a variable after it is declared? B. No 17

Accessing value, Lvalue and Rvalue To access/change the value of a basic type: y=x; x=10; 102 y= x>y? x : y; x 20 18

Accessing location To access the location/address, use the address operator & &x (is 102) 102 x 20 19

Pointers Pointer: A variable that contains the address of a variable int *x; 20

Pointers Pointer: A variable that contains the address of a variable int *x, y; 102 120 x" y" y = 3; x = &y; 21

Pointers Pointer: A variable that contains the address of a variable int *x, y; y = 3; x = &y; sizeof(x)= 102 120 x"?" y"?" 102 120 x"?" y" 3" 102 120 x" 120! y" 3" x points to y 22

Pointer Diagrams Short hand diagram for the following scenario 102 120 x" 120! y" 3" 23

Using pointers to change the value of a variable Use dereference * operator to left of pointer name x" y" 3" x" y" 3" *x = 5; 24

Two ways of changing the value of any variable Why this is useful will be clear when we discuss functions and pointers x" y" 3" *x = 5; x" y" 5" 25

Pointers and Pointees int *p1, *p2, x; p1 = &x; p2 = p1; Q: Which of the following pointer diagrams best represents the outcome of the above code? A. x" B. x" C. Neither, the code is incorrect 26

Pointer and Pointee data types Q: This code gives a warning at compile time. Why? char *p; int y =10000; p = &y; A. The pointer p is made to point to a variable of incompatible type B. *p does not contain a valid value because y was not initialized 27

Q: Does the following code give an error at run time? A. Yes B. No int *p; *p = 5; 28

Q: What is the output of this code? int *p, x = 5; printf( %d,(*p)++); A. The value pointed to by p, which is 5 B. The value pointed to by p plus one, which is 6 C. UndeHined 29

Two important facts about Pointers 1) A pointer can only point to one type (basic or derived ) such as int, char, a struct, another pointer, etc 2) After declaring a pointer: int *ptr; ptr doesn t actually point to anything yet. We can either: Ø make it point to something that already exists, or Ø allocate room in memory for something new that it will point to (next lecture) 30

Array Basics ar 100 104 108 112 116 " int ar[5]; // declares a 5-element integer array 31

Array Basics ar 100 104 108 112 116 " int ar[5]; // declares a 5-element integer array int ar[] = {795, 635}; //declares and fills a 2- element integer array. 32

Array Basics ar 100 104 108 112 116 " 20 Accessing elements: ar[i];// returns the i th element How are arrays in C different from Java? Pointers and arrays are very similar 33

Arrays and Pointers ar 100 104 108 112 116 " 20 ar is a pointer to the first element ar[0] is the same as *ar ar[2] is the same as *(ar+2)

Arrays and Pointers ar 100 104 108 112 116 " 20 Use pointers to pass arrays to functions Use pointer arithmetic to access arrays more conveniently

Pointer Arithmetic Since a pointer is just a memory address, we can add to it to traverse an array. ptr+1 will return a pointer to the next array element. ptr 100 104 108 112 116 " 20 40 60

Pointer Arithmetic ptr *ptr+1 =? *ptr++ =? *(ptr+1)=? 100 104 108 112 116 " 20 40 60 A. 21, 20, 40 B. 21, 21, 40 C. 21, 40, 40

Arrays: Fast data access Using pointer arithmetic, easy to compute the address of any array element in memory How are array elements accessed on an ARM? ptr 100 104 108 112 116 " 20 40 60 Base address (100) register Processor Address Data Memory

Restrictions on memory access Not all of memory is accessible by your program ptr 100 104 108 112 116 " 20 40 60 Base address (100) register Processor Address Data Memory

Q: Which of the assignment statements produces an error at compilation. Why? int *p, ar[5]; //Declaration i) p=ar+5; ii)ar=p+1; ar 100 104 108 112 116 " p 20 A. p=ar+5; B. ar=p+1; C. Both statements result in error at compile time D. Neither results in a compilation error

Q: What happens when the following code is executed? int *p, ar[5]; //Declaration p=ar- 5; *p=0; A. Always results in a segmentation fault because a pointer cannot be used to change the value of an array element B. Always results in a segmentation fault because the array element being accessed is out of bounds C. Likely to result in a segmentation fault because the memory location being accessed may not be a valid address D. It results in a compilation error

Arrays Pitfall: An array in C does not know its own length, & bounds not checked! Consequence: We can accidentally access off the end of an array. Consequence: We must pass the array and its size to a procedure which is going to traverse it. Segmentation faults and bus errors: These are VERY difficult to find, so be careful.

Pointer Arithmetic What if we have an array of large structs (objects)? C takes care of it: In reality, ptr+1 doesn t add 1 to the memory address, but rather adds the size of the array element. C knows the size of the thing a pointer points to every addition or subtraction moves that many bytes: 1 byte for a char, 4 bytes for an int, etc.

Pointer Arithmetic Question How many of the following are invalid? I. pointer + integer (ptr+1) II. integer + pointer (1+ptr) III. pointer + pointer (ptr + ptr) IV. pointer integer (ptr 1) V. integer pointer (1 ptr) VI. pointer pointer (ptr ptr) VII. compare pointer to pointer (ptr == ptr) VIII. compare pointer to integer (1 == ptr) IX. compare pointer to 0 (ptr == NULL) X. compare pointer to NULL (ptr == NULL) #invalid A: 1 B: 2 C: 3 D: 4 E: 5

Pointer Arithmetic Question How many of the following are invalid? I. pointer + integer (ptr+1) II. integer + pointer (1+ptr) III. pointer + pointer (ptr + ptr) IV. pointer integer (ptr 1) V. integer pointer (1 ptr) VI. pointer pointer (ptr ptr) VII. compare pointer to pointer (ptr == ptr) VIII. compare pointer to integer (1 == ptr) IX. compare pointer to 0 (ptr == NULL) X. compare pointer to NULL (ptr == NULL) #invalid A: 1 B: 2 C: 3 D: 4 E: 5

Functions: Breaking large computing tasks to smaller ones 46

C Programming Procedural thought process main () /* High level Outline */ {... get_input(arg1) /*Comment: Step 1 */ perform_step_2(arg2); perform_step_3(); store_result(); /* Print output or store in a file */ } 47

Overview of Functions Functions make code easy to Maintain Debug Reuse 48

Functions Overview void foo(int x, int y); //Declaration 49

//De<inition Functions Overview void foo(int x, int y) { int tmp; tmp= x; x= y; y= tmp; } What does foo do? tmp x foo y 50

Stack Allocation: Function local variables and parameters When program execution starts Local variables of func() Other information about func() Local variables of main() What if main calls the function func()? Stack Pointer 51

Stack Allocation: Function local variables and parameters Local variables of main() Stack Pointer 52

Scope Variables declared within a function can be used: A. By other functions B. Only within the function 53

Lifetime of data Lifetime: The interval between time of creation and end of existence of data 54

Possible lifetimes of data 1. Execution time of program 2. Time between explicit creation and explicit deletion 3. Execution time of a function (time between function call and function return) *Variables whose lifetime is the execution time of function are managed using the stack structure 55

Specifying Scope and Lifetime Scope and lifetime are often implicit but sometimes we have to use specihic keywords: static int a=0; /*DeHines lifetime*/ extern int a; /*Extends scope to multiple Hiles*/ 56

Different types of data What factor differentiates the following three categories of data in a C program: Global and static variables Local variables Dynamic variables A. Scope B. Lifetime C. Representation 57

Different types of data What factor differentiates the following three categories of data in a C program: Global and static variables Local variables Dynamic variables A. Scope B. Lifetime C. Representation 58

Functions: Call by value main() {... 5 6 x swap(a, b); a b.... } swap y Q: Are the value of variables a and b interchanged after swap is called? A. Yes, because that s what is implemented by the swap routine B. No, because the inputs to swap are only copies of a and b 59

Functions: Call by value main() {... 5 6 x swap(a, b); a b.... } swap y Q: Are the value of variables a and b interchanged after swap is called? A. Yes, because that s what is implemented by the swap routine B. No, because the inputs to swap are only copies of a and b 60

Q: Which of the following changes are required to interchange the values in a and b when swap is called? {.... swap(a, b); } a 5 6 b x swap y A. In swap, return the values of x and y to the main function after swapping them B. Declare a and b as global variables, so that they become accessible to the swap routine C. Pass the address of a and b to swap instead of their value D. Move the implementation in swap to the main function 61

Q: Which of the following changes are required to interchange the values in a and b when swap is called? {.... swap(a, b); } a 5 6 b x swap y A. In swap, return the values of x and y to the main function after swapping them B. Declare a and b as global variables, so that they become accessible to the swap routine C. Pass the address of a and b to swap instead of their value D. Move the implementation in swap to the main function 62

Functions: Call by reference void swap(int *x, int *y) {... } Q: What should the modihied swap function do? A. Swap the addresses in x and y B. Swap the values pointed to by x and y C. Both the above operations are equivalent 63

Functions: Call by reference void swap(int *x, int *y) {... } Q: What should the modihied swap function do? A. Swap the addresses in x and y B. Swap the values pointed to by x and y C. Both the above operations are equivalent 64

void IncrementPtr(int *p){ p = p + 1; } Q: What happens when IncrementPtr(q)is called in the following code: A q int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); 50 60 70 A. The pointer q points to the next element in the array with value 60 B. The pointer q points to the first element in the array with value 50

void IncrementPtr(int *p){ p = p + 1; } Q: What happens when IncrementPtr(q)is called in the following code: A q int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); 50 60 70 A. The pointer q points to the next element in the array with value 60 B. The pointer q points to the first element in the array with value 50

void IncrementPtr(int **p){ p = p + 1; } Q: How should we implement IncrementPtr(),so that q moves by one element when the following code executes? int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); A q 50 60 70 A. p = p + 1; //The current one is correct B. &p = &p + 1; C. *p= *p + 1; D. *p++; E. p= &p+1;

void IncrementPtr(int **p){ p = p + 1; } Q: How should we implement IncrementPtr(),so that q moves by one element when the following code executes? int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); A q 50 60 70 A. p = p + 1; //The current one is correct B. &p = &p + 1; C. *p= *p + 1; D. *p++; E. p= &p+1;

What is really in a executable % gcc hello.c %./a.out (executable loaded in memory and processed) Also referred to as running the C program gcc hello.c Source : Program in C a.out Executable : Equivalent program in machine language 69

What does the executable contain? Instructions or code Data What is data? Any information that instructions operate on (objects in memory) 70

C Runtime Environment Code (instructions in machine language) Data (initialized and uninitialized - static allocated) Both code and data don t change in size Heap (for dynamically allocated data) Stack (for function local variables) Heap and stack change in size as the program executes 71

C Runtime Environment Code Initialized Data Uninitialized Data Heap Stack 72