CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

Similar documents
Intro. Scheme Basics. scm> 5 5. scm>

CS 61c: Great Ideas in Computer Architecture

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

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

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

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

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

CS 222: Pointers and Manual Memory Management

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

A brief introduction to C programming for Java programmers

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

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

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

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

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

Type Checking and Type Equality

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intermediate Programming, Spring 2017*

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

CS 326: Operating Systems. Process Execution. Lecture 5

CS61C : Machine Structures

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

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

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

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

CSE 374 Programming Concepts & Tools

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

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Lecture 03 Bits, Bytes and Data Types

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

CS 107 Lecture 5: Arrays. and Pointers in C. Monday, January 22, Stanford University. Computer Science Department

ECEN 449 Microprocessor System Design. Review of C Programming

CSE 374 Programming Concepts & Tools

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

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

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

Homework #3 CS2255 Fall 2012

CS558 Programming Languages

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

Starting to Program in C++ (Basics & I/O)

Lecture 4 CSE July 1992

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CSE 303: Concepts and Tools for Software Development

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

arrays and strings week 3 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 22 imperative programming review

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

CS61C : Machine Structures

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

Introduction to Scientific Computing and Problem Solving

CS2141 Software Development using C/C++ C++ Basics

Variables and Data Representation

CS 137 Part 2. Loops, Functions, Recursion, Arrays. September 22nd, 2017

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

These are notes for the third lecture; if statements and loops.

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

C Pointers 2013 Author Riko H i

Lecture 5: Implementing Lists, Version 1

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

C++ for Java Programmers

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Page 1. Today. Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right? Compiler requirements CPP Volatile

Reference operator (&)

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

Operating systems. Lecture 7

CS Programming In C

CS24 Week 2 Lecture 1

CS61C : Machine Structures

Lecture Topics. Administrivia

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Chapter 7. Basic Types

CS 6371: Advanced Programming Languages

by Pearson Education, Inc. All Rights Reserved.

Project Compiler. CS031 TA Help Session November 28, 2011

Heap Arrays and Linked Lists. Steven R. Bagley

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

PRINCIPLES OF OPERATING SYSTEMS

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Pointers (continued), arrays and strings

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

Pointers in C/C++ 1 Memory Addresses 2

CS354 gdb Tutorial Written by Chris Feilbach

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Topics Introduction to Microprocessors

CS558 Programming Languages

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

Variables and literals

Lecture 07 Debugging Programs with GDB

QUIZ. What are 3 differences between C and C++ const variables?

Transcription:

CS 220: Introduction to Parallel Computing Arrays Lecture 4

Note: Windows I updated the VM image on the website It now includes: Sublime text Gitkraken (a nice git GUI) And the git command line tools 1/30/18 CS 220: Parallel Computing 2

Today s Agenda Argument Passing in C Compilation Phases Arrays 1/30/18 CS 220: Parallel Computing 3

Today s Agenda Argument Passing in C Compilation Phases Arrays 1/30/18 CS 220: Parallel Computing 4

Argument Passing Conventions Coming from the Java or Python world, we re used to passing inputs to our functions The result of the function is given to us in the return value There are situations where this convention does not hold, but it s less common This is not the case with C 1/30/18 CS 220: Parallel Computing 5

An Example /* Here's a function that increments * an integer. */ void add_one(int *i) { *i = *i + 1; } int a = 6; add_one(&a); /* a is now 7 */ 1/30/18 CS 220: Parallel Computing 6

C In/Out Arguments In C, some of the function arguments serve as outputs Or in the example we just saw, the function argument is both an input and an output! Some API designers even label these arguments as in or out args (example from the Windows API): BOOL WINAPI FindNextFile( _In_ HANDLE hfindfile, _Out_ LPWIN32_FIND_DATA lpfindfiledata ); Why? 1/30/18 CS 220: Parallel Computing 7

Error Reporting One reason for this is C does not have exceptions Problem in a Java/Python function? Throw an exception! In C, the return value of functions often indicates success or failure (bool) Or a maybe something in between (int) status code Functions don t have to be designed this way, but it s a very common convention 1/30/18 CS 220: Parallel Computing 8

Efficiency Return values have to be copied back to the calling function Say my function returns a bitmap image. The entire thing is going to get copied! In a language that focuses on speed and efficiency, updating the values directly in memory is faster Imagine transferring lots of large strings, objects, etc. around your program, copying them between functions each and every time 1/30/18 CS 220: Parallel Computing 9

C Argument Passing So remember: the return value in C might not actually be the result of the function It may just be an error code or status code It might just be a Boolean True means success, false means failure Or maybe one of the function inputs was modified directly instead Efficiency benefits 1/30/18 CS 220: Parallel Computing 10

Void Argument (1/3) In C, there s a difference between function() and function(void) Void arg: the function takes no arguments Empty arg list: the function may or may not take arguments If it does, they can be of any type and there can be any number of them 1/30/18 CS 220: Parallel Computing 11

Void Argument (2/3) Why is this important? First, to understand older code From the C11 standard: The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature. Second, this may lead to incorrect function prototypes or passing incorrect args in your code 1/30/18 CS 220: Parallel Computing 12

Void Argument (3/3) So, to sum up: /* Takes an unspecified number of args: */ void function(); /* Takes no args: */ void function(void); 1/30/18 CS 220: Parallel Computing 13

Today s Agenda Argument Passing in C Compilation Phases Arrays 1/30/18 CS 220: Parallel Computing 14

Recall: Phases of C Compilation 1. Preprocessing: perform text substitution, include files, and define macros. The first pass of compilation. Directives begin with a # 2. Translation: preprocessed code is converted to machine language (also known as object code) 3. Linking: your code likely uses external routines (for example, printf from stdio.h). In this phase, libraries are added to your code 1/30/18 CS 220: Parallel Computing 15

Stepping Through Compilation When we compile our source code, we get an output binary that is ready to run The steps are mostly invisible to us We can ask the compiler to only execute a subset of its compilation phases Let s do just that! 1/30/18 CS 220: Parallel Computing 16

Preprocessing We can ask gcc to only perform the preprocessing step using the -E flag: gcc -E my_program.c This will print the preprocessed file to the terminal We can write this output to a file by redirecting the stdout (standard output) stream: gcc -E my_program.c > my_program.pre And view with a text editor 1/30/18 CS 220: Parallel Computing 17

Translating to Assembly Code We can also view the assembly code generated by the compiler gcc -S my_program.c Produces my_program.s This representation is very close to the underlying machine code For a reference on x86-64 processor assembly: https://web.stanford.edu/class/cs107/guide_x86-64.html 1/30/18 CS 220: Parallel Computing 18

Producing Object Code Finally, we can produce the machine code / object code representation of the program gcc -c my_program.c Produces my_program.o We can view this with a hex editor hexdump -C my_program.o 1/30/18 CS 220: Parallel Computing 19

Linking Finally, our object code is linked against the other necessary libraries to create an executable Nothing to inspect here, but we can always view the output binary in a hex editor: hexdump -C my_program 1/30/18 CS 220: Parallel Computing 20

Today s Agenda Argument Passing in C Compilation Phases Arrays 1/30/18 CS 220: Parallel Computing 21

Arrays In C, arrays let us store a collection of values of the same type They are similar to the arrays in Java, and roughly analogous to the lists in Python However, Python lets us store values of different types: my_list = [ 1, 6.8, San Francisco ] In C, an array is nothing more than a block of memory set aside for a collection of a particular type 1/30/18 CS 220: Parallel Computing 22

Creating an Array In Java: int[] numbers = new int[100]; In Python: numbers = [] In C: int list[10]; double dlist[15]; Note that here, the arrays must be dimensioned when they re declared In older versions of C the dimension had to be a constant 1/30/18 CS 220: Parallel Computing 23

Accessing Array Elements Retrieving the values of an array is the same as it is in Java: list[2] = 7; list[1] = list[2] + 3; However, one interesting note about C is there is no boundary checking, so: list[10] = 7; dlist[17] = 2.0; may work just fine. 1/30/18 CS 220: Parallel Computing 24

Experiment: When will it Break? We can try modifying out-of-bounds array elements We can even do it in a loop to test the limits Different operating systems / architectures may react differently Let s demo this now At this point, you might be wondering: What is wrong with C?! What is the meaning of life? 1/30/18 CS 220: Parallel Computing 25

Accessing Array Values So we can do things like this in C: int list[5]; list[10] = 7; Your program may work fine or crash! It s never a good idea to do this So why does C let us do it anyway? 1/30/18 CS 220: Parallel Computing 26

Safety and Performance C favors performance over safety Compare: C program vs Python equivalent Helpful: time command Especially in the glory days of C, adding lots of extra checks meant poor performance Extra if statement for each array access, etc Sometimes these safety features aren t necessary Especially for perfect programmers? You can always implement safety features yourself 1/30/18 CS 220: Parallel Computing 27

Creating an Array Let s create our list of integers: int list[10]; When we do this, C sets aside a place in memory for the array It doesn t clear the memory unless we ask it to A common cause of subtle bugs Creating a list of integers initialized to zero: int list[10] = { 0 }; 1/30/18 CS 220: Parallel Computing 28

Memory Access What happens when you retrieve the value of list[5]? 1. Find the location of list in memory 2. Move to the proper offset: 5 * 4 = byte 20 3. Access the value Accessing list[500] is just moving to a position in memory and retrieving whatever is there 1/30/18 CS 220: Parallel Computing 29

Visualizing Arrays in Memory /* Note: can calculate array * dimensions automatically! */ int list[] = { 0, 1, 15, 2001 }; 4 Elements (4 * 4) = 16 byte array sizeof(int) = 4 (4 bytes) 1/30/18 CS 220: Parallel Computing 30

The sizeof operator We can use the sizeof operator in C to determine how big things are Somewhat like: len() in python.length in Java, or.size() in Java Much more low-level size_t sz = sizeof(int); printf("%zd\n", sz); // Prints 4 (on my machine) 1/30/18 CS 220: Parallel Computing 31

Array Size (1/2) Let s try this out: int list[10]; size_t list_sz = sizeof(list); Any guesses on the output? On my machine, it s 40: 40 bytes (10 integers at 4 bytes each) This can be different depending on architecture In C, sizeof(char) is guaranteed to be 1. 1/30/18 CS 220: Parallel Computing 32

Array Size (2/2) Knowing the number of bytes in the array can be useful, but not that useful Usually we want to know how many elements there are in an array To do this, we ll divide by the array type (int - 4 bytes): int list[10]; size_t list_sz = sizeof(list) / sizeof(list[0]); printf("%zd\n", list_sz); /* Prints 10 (on my machine) */ 1/30/18 CS 220: Parallel Computing 33

Behind the Scenes Arrays in C are actually pointers int list[5]; list is the same as &list[0]; You can t change what they point at, but otherwise they work the same So accessing list[2] is really just dereferencing a pointer that points two memory addresses from the start of the array ever think about why we used 0-based arrays in CS? 1/30/18 CS 220: Parallel Computing 34

We can make this more fun Since arrays are just constant pointers, we have another way to access them: list[5] Is the same thing as: *(list + 5) Workflow: 1. Locate the start of the array 2. Move up 5 memory locations (4 bytes each*) 3. Dereference the pointer to get our value 1/30/18 CS 220: Parallel Computing 35

Pointer Arithmetic Manipulating pointers in this way is called pointer arithmetic arr[i]; is the same as *(arr + i); arr[6] = 42; is the same as *(arr + 6) = 42; 1/30/18 CS 220: Parallel Computing 36

Visualizing Arrays int list[] = { 0, 1, 15, 2001 }; sizeof(int) = 4 1/30/18 CS 220: Parallel Computing 37

A Note on Pointer Arithmetic In general, stick with using regular array syntax You may see pointer arithmetic in production code, but it should only be used in situations that make the code more understandable Haphazardly showing off your knowledge of pointer arithmetic is a recipe for confusing code 1/30/18 CS 220: Parallel Computing 38

Arrays as Function Arguments When we pass an array to a function, its pointerbased underpinnings begin to show If we modify an array element inside a function, will the change be reflected in the calling function? Why? In fact, when an array is passed to a function it decays to a pointer The function just receives a pointer to the first element in the array. That s it! 1/30/18 CS 220: Parallel Computing 39

Array Decay When an array decays to a pointer, we lose some information Type and dimension Let s imagine someone just gives us a pointer Do we know if it points to a single value? Is it the start of an array? Functions are in the same situation: they don t know where this pointer came from or where it s been sizeof doesn t work as expected 1/30/18 CS 220: Parallel Computing 40

Avoiding Decay decay.c:22:19: warning: sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Wsizeof-array-argument] sizeof(list), To avoid this situation, we need to pass in the size of the array as well. You may have wondered why the sizes of arrays are always being passed around in C code This is why! 1/30/18 CS 220: Parallel Computing 41

Homework 1: Arrays Let s get started on HW1 (posted on the course website) This homework introduces you to a few new functions and gives you a chance to play with arrays 1/30/18 CS 220: Parallel Computing 42