COMP 2355 Introduction to Systems Programming

Similar documents
Pointers, Arrays, and Strings. CS449 Spring 2016

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Memory, Arrays & Pointers

COMP 2355 Introduction to Systems Programming

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

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

Pointers, Dynamic Data, and Reference Types

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Introduction to Programming Block Tutorial C/C++

High Performance Programming Programming in C part 1

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Create a Program in C (Last Class)

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Principles of C and Memory Management

Computer Programming: Skills & Concepts (CP) Strings

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Dynamic Allocation in C

Kurt Schmidt. October 30, 2018

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

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

PRINCIPLES OF OPERATING SYSTEMS

Memory Corruption 101 From Primitives to Exploit

CS 0449 Sample Midterm

Memory Allocation. General Questions

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

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CSE2301. Arrays and Pointers. These slides are based on slides by Prof. Wolfgang Stuerzlinger at York University. Arrays

CSE2301. Arrays. Arrays. Arrays and Pointers

Programming refresher and intro to C programming

211: Computer Architecture Summer 2016

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Common Misunderstandings from Exam 1 Material

Memory Corruption Vulnerabilities, Part II

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Programming in C. Pointers and Arrays

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

Contents of Lecture 3

C++ for Java Programmers

Arrays and Pointers in C. Alan L. Cox

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

CSE2301. Arrays. Arrays. Arrays and Pointers

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

Fundamental of Programming (C)

EL2310 Scientific Programming

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

Work relative to other classes

TDDB68 Concurrent Programming and Operating Systems. Lecture 2: Introduction to C programming

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

ELEC 377 C Programming Tutorial. ELEC Operating Systems

ME964 High Performance Computing for Engineering Applications

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Contents. A Review of C language. Visual C Visual C++ 6.0

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

POINTER & REFERENCE VARIABLES

Pointers. Pointer References

CSC C69: OPERATING SYSTEMS

CS 241 Data Organization Pointers and Arrays

Lecture 05 Pointers ctd..

CS201- Introduction to Programming Current Quizzes

CS C Primer. Tyler Szepesi. January 16, 2013

Memory Organization. The machine code and data associated with it are in the code segment

CS 61c: Great Ideas in Computer Architecture

Data Types (cont.) Subset. subtype in Ada. Powerset. set of in Pascal. implementations. CSE 3302 Programming Languages 10/1/2007

CSE 333 Lecture 2 Memory

Arrays and Strings. CS449 Fall 2017

Question 1. [15 marks]

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Array Initialization

EL2310 Scientific Programming

Winter 2017 CS107 Midterm #2 Examination (Practice #2) Problem Points Score Grader TOTAL 30

EL2310 Scientific Programming

CSE 12 Spring 2016 Week One, Lecture Two

Low-Level Programming in C

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Systems Programming and Computer Architecture ( )

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

ECE551 Midterm Version 2

Lecture 04 Introduction to pointers

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

Arrays, Pointers and Memory Management

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

Dynamic Allocation in C

Programming in C - Part 2

Transcription:

COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1

Pointers Pointers denote addresses in memory In C types, the * represents the use of a pointer Pointers always have a base-type: int * or union foo * The base-type specifies the type of the data at that location in memory Pointers are similar to references in Java 2

The Address-Of Operator You can obtain the address of a variable using the & operator The resulting value is always a pointer Example: int i; int * i_ptr = &i; 3

The Address-Of Operator You can not take the address of a constant: int * i_ptr = &5; will not compile! 4

The Address-Of Operator Note that & is also used for bitwise-and: int one = 3 & 5; // bitwise-and int * ptr = &one; // address-of 5

The Dereferencing Operator The * operator is the inverse of the & operator: int i = 4; int * i_ptr = &i; int j = *i_ptr; // j = 4 (*i_ptr) = 6; // i = 6, j = 4 6

Dereferencing structs and unions You can use the -> operator to dereference a struct or union if you are also selecting a field: struct foo { int a; int b; }; struct foo * fodder; fodder = malloc(sizeof(struct foo)); fodder->a = 4; (*fodder).b = 4; 7

Returning multiple values using pointers void run(int a1, int a2, int * r1, int * r2) { *r1 = a1 + a2; *r2 = a1 * a2; } int main(int argc, char ** argv) { int p, m; run(3, 4, &p, &m); printf("%d %d\n", p, m); } 8

Arrays Arrays in C are always from [0 : n 1] (like in Java) C does not support bounds checking on array access Results of accessing arrays out of bounds are undefined Arrays are implemented using pointers You will only fully understand them after lecture 6 9

Array Types In some sense, arrays are pointers. situation, C uses either: Depending on the int * a; // works always int a[]; // for parameters int a[size]; // for stack allocation 10

Allocating Arrays: on stack int main(int argc, char * argv[]) { int myarray[10]; int i; myarray[0] = 1; myarray[1] = 1; for (i=2;i<10;i++) myarray[i] = myarray[i-1] + myarray[i-2]; printf("%d\n", myarray[9]); return 0; } 11

Allocating Arrays: on stack static int * fib() { int myarray[10]; int i; myarray[0] = 1; myarray[1] = 1; for (i=2;i<10;i++) myarray[i] = myarray[i-1] + myarray[i-2]; return myarray; // compiler warning! } int main(int argc, char * argv[]) { int * a = fib(); printf("%d\n", a[9]); // undefined! return 0; } 12

Allocating Arrays: on the heap static int * fib() { int * myarray; int i; myarray = malloc(sizeof(int) * 10); myarray[0] = 1; myarray[1] = 1; for (i=2;i<10;i++) myarray[i] = myarray[i-1] + myarray[i-2]; return myarray; } int main(int argc, char * argv[]) { int * a = fib(); printf("%d\n", a[9]); free(a); return 0; } 13

So what should you use? Use BASETYPE * a; // almost always BASETYPE a[] // only (legal) for function arguments if you want to stress a s nature as an array BASETYPE a[size]; is the only legal syntax for stackallocation. 14

Multidimensional Arrays int ** a; int a[][]; int * a[]; // common for argv 15

Heap-Allocation of Multidimensional Arrays static int ** matrix() { int ** ret; int i; ret = malloc(sizeof(int*) * 100); for (i=0;i<100;i++) ret[i] = malloc(sizeof(int) * 100); return ret; } int main(int argc, char * argv[]) { int ** m; int i; m = matrix(); for (i=0;i<100;i++) free(a[i]); free(a); return 0; } 16

Heap-Allocation of Multidimensional Arrays /* define IA as array of 100 integers */ typedef int IA[100]; static IA * matrix() { IA * ret; int i; ret = malloc(sizeof(ia) * 100); return ret; } int main(int argc, char * argv[]) { IA * m; int i; m = matrix(); free(m); return 0; } 17

Array Initialization int primes[] = { 2, 3, 5, 7, 11, 13 }; void print_primes() { unsigned int offset; } for (i=0;i<sizeof(primes)/sizeof(int);i++) printf("%d\n", primes[i]); 18

Array Initialization int primes[] = { 2, 3, 5, 7, 11, 13, -1 }; void print_primes() { unsigned int offset; } offset = 0; while (primes[offset]!= -1) printf("%d\n", primes[offset++]); 19

const const is a type modifier used to hint that the memory referred to by a pointer should not be modified. Example: void print_array(const int * arr, unsigned int len) { unsigned int i; for (i=0;i<len;i++) printf("%d ", arr[i]); // ok arr[0] = 42; // compiler error } 20

C is not type-safe It is possible to cast a const variable: Example: void print_array(const int * arr, unsigned int len) { unsigned int i; for (i=0;i<len;i++) printf("%d ", arr[i]); // ok ((int*)arr)[0] = 42; // compiler happy } 21

Strings Strings in C are arrays of characters (char) Strings should always be 0-terminated Not all char* or char[] are strings! Programmer is responsible for 0-termination! Major source of bugs in C code! 22

Strings What happens if you write "Hello World" in C? C compiler creates 0-terminated char array Precise type of the value is const char * String is allocated in data area; do not modify! If the same string occurs multiple times, compiler may alias data area. "Hello World"[4] == o 23

Common String Functions size t strlen(const char *) char * strstr(const char * haystack, const char * needle); int strcmp(const char * s1, const char * s2); char * strcpy(char * dest, const char * src); char * strcat(char * dest, const char * src); Homework: study the man pages for these functions! 24

Example: strdup char * strdup(const char * s) { char * ret; size_t i; } ret = malloc(strlen(s) + 1); for (i=0;i<strlen(s)+1;i++) ret[i] = s[i]; return ret; 25

Array Initialization Revisited struct Student { const char * name; unsigned int age; }; struct Student students[] = { { "Alice", 19 }, { "Bob", 21 }, { "Carol", 27 }, { "Dave", 31 }, { NULL, 0 } }; 26

Variadic Functions Variadic functions take a variable number of arguments In Java (since 5.0) implemented using arrays More complicated story in C... 27

Defining Variadic Functions Variadic functions must take at least one normal argument Use... at the end to specify 0 or more additional arguments Example: int printf(const char * format,...); 28

Accessing the arguments int print_ints(unsigned int number_of_args,...) va_list va; unsigned int i; va_start(va, number_of_args); for (i=0;i<number_of_args;i++) printf("%d", va_arg(va, int)); va_end(va); } 29

Fun with Variadic Functions (1/3) int print_stuff(const char * format,...) { va_list va; unsigned int i; va_start(va, format); i = 0; while (format[i]!= \0 ) { //... (see next slide) } va_end(va); } 30

Fun with Variadic Functions (2/3) switch (format[i]) { case i : printf("%d", va_arg(va, int)); break; case s : printf("%s", va_arg(va, const char*)); break; case f : printf("%f", va_arg(va, float)); break; case x : printf("%4s", va_arg(va, struct Student*)->name); break; default: abort(); } 31

Fun with Variadic Functions (3/3) int main(int argc, char ** argv) { struct Student alice; alice.name = "Alice"; print_stuff("isf", 42, "Test", 4.2); print_stuff("xsi", &alice, "Test", 1); print_stuff("ifs", 1, 2, 3); /* crash! */ return 0; } 32

printf (1/3) int printf(const char * format,...); Prints format-string, uses arguments to determine values conversion specifications (which start with %). Homework: Read man 3 printf! 33

printf (2/3) %d print int (decimal) %u print unsigned int %x print unsigned int (hexadecimal) %o print unsigned int (octal) %f print double %s print const char * 34

printf (3/3) %08d print 8 characters of int, padd with zeros %.3f print double with 3 decimal places %5s print first five characters of const char * %.*s print unsigned int characters of const char * %p print void * (any pointer/address) 35

Questions? 36