C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

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

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

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

CSCI 171 Chapter Outlines

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

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

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

Lectures 5-6: Introduction to C

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

Lectures 5-6: Introduction to C

The C Programming Language Guide for the Robot Course work Module

SYSC 2006 C Winter 2012

CSE 374 Programming Concepts & Tools

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Review of the C Programming Language for Principles of Operating Systems

Motivation was to facilitate development of systems software, especially OS development.

Chapter IV Introduction to C for Java programmers

A Fast Review of C Essentials Part I

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

EL6483: Brief Overview of C Programming Language

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Review of the C Programming Language

CS 11 C track: lecture 5

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

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Lecture 04 Introduction to pointers

0x0d2C May your signals all trap May your references be bounded All memory aligned Floats to ints round. remember...

EL2310 Scientific Programming

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

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

BLM2031 Structured Programming. Zeyneb KURT

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Quiz 0 Review Session. October 13th, 2014

377 Student Guide to C++

Motivation was to facilitate development of systems software, especially OS development.

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Programming in C - Part 2

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

QUIZ. Source:

Kurt Schmidt. October 30, 2018

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

Intermediate Programming, Spring 2017*

ECE264 Spring 2013 Final Exam, April 30, 2013

Variables and literals

Technical Questions. Q 1) What are the key features in C programming language?

EL2310 Scientific Programming

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Lecture 03 Bits, Bytes and Data Types

Decision Making -Branching. Class Incharge: S. Sasirekha

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

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Dynamic memory allocation (malloc)

by Pearson Education, Inc. All Rights Reserved.

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

More about BOOLEAN issues

Programs in memory. The layout of memory is roughly:

Introduction to C: Pointers

CS61, Fall 2012 Section 2 Notes

CS 61c: Great Ideas in Computer Architecture

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

Fundamental of Programming (C)

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

CSCI 350: Getting Started with C Written by: Stephen Tsung-Han Sher June 12, 2016

a data type is Types

Model Viva Questions for Programming in C lab

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

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

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

Understanding Pointers


Have examined process Creating program Have developed program Written in C Source code

C++ Tutorial AM 225. Dan Fortunato

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

C++ Programming Chapter 7 Pointers

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

Arrays and Pointers in C & C++

ch = argv[i][++j]; /* why does ++j but j++ does not? */

CS61C : Machine Structures

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

C Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS

Heap Arrays and Linked Lists. Steven R. Bagley

A brief introduction to C programming for Java programmers

Memory Corruption 101 From Primitives to Exploit

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

ECE 15B COMPUTER ORGANIZATION

A Quick Introduction to C Programming

Dynamic memory allocation

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CMPE-013/L. Introduction to C Programming

Heap Arrays. Steven R. Bagley

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Transcription:

C Review MaxMSP Developers Workshop Summer 2009 CNMAT

C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (*** IMPORTANT ***) Preprocessor directives, macros Compiling, linking, debugging

Syntax Code blocks in { } Every line ends with ; Whitespace is ignored Control order-of-evaluation for expressions with ( ) (i.e. just like in math) Strings are surrounded by Special compiler-stuff begins with # Comments start with // or surround with /*... */

Flow Control while: loop until a test is false for: run a start action, loop until a test is false, do some action between each iteration do: loop until a test is false with a minimum of one run switch: jump to a point in the program based on a value if, else: run some code if a test is true, otherwise do something else goto: jump immediately to a named location

Function Prototype int myfunc(int argc, char* argv); Return type: int Name of function: myfunc Input type(s): int, char*

The Main Function int main() { // do something here //... // all done! return 0; } main automatically executes when your program is loaded. when main returns the program is done (unless there are other threads still running)

Header Files #include <stdio.h> int main() { printf("hello World\n"); return 0; } Has the.h extension Contains a collection of function prototypes so the compiler knows what types a function takes and returns (e.g. what does printf do?)

Variables Every variable has a fixed type that cannot be changed. (static type) The number of bytes taken by a type is given by sizeof(). You can make up your own types by combining other types and declare them with typedef. Usually they are named like t_something

Global Variables int x; void add_to_x(int y) { x = x + y; }

Local Variables int sum_up_to(int x) { int s; int i; s = 0; for(i = 0; i <= x; i++) { s = s + i; } } return s;

Type Declarations A type declaration creates a variable of a defined type and gives it a name. Every named variable has to have a type declaration. Every named variable exists either on The Heap (global scope, lives forever) or The Stack (in a function, lives until the function returns).

Type Declarations int x; let x be of type int

Basic Types // Integer int x; // Float (real number with decimals) float f; // A float with extra accuracy (good to use) double d; // Many things of the same type int a, b, c, d; // A single letter char letter; // A bunch of letters (string) char* foo = foo ;

Expressions An expression is a bit of code that is evaluated The result of an expression is always a known type, called the return type The return type is determined by the compiler by analyzing the code

Assignment with = // = means assignment a = 4 * 6; // assignment can self-reference a = a + 5; // == tests if a is equal to 5 a == 5;

Expressions (6 * 7); the int that is 6 times 7

Typecasting You can force a return type to be transformed to another type by using a typecast. Unless the compiler knows how to interpret your typecast, the results may be unexpected. Avoid using typecasts whenever possible. C++ fixes the bad behavior of typecasts.

Expressions with Type Casting (float)(6 * 7); change the int that is 6 times 7 into a float

Assignment An expression can be assigned to a variable. The return type of the expression must match the declared type of the variable Assignment works on entire structures also.

Expressions int x; x = (6 * 7); let x be of type int. x gets the int that is 6 times 7.

Pointer to a Type There is a meta type that is a pointer to any defined type. This type can be declared using the * operator in a type declaration.

Declaring a Pointer to a Type int *x; let x be a pointer that when dereferenced is an int

Point of Confusion with * int *x; int* x; Both mean the same thing.

Pointer to an Unknown Type void *x; let x be a pointer that when dereferenced is an unknown thing

Address-of Address-of, &, is an operator that returns a pointer to whatever it is prefixed to.

Pointer to a Type int y; int *x; Note &y is an rvalue x = &y; let y be an int. let x be of type pointer-to-an-int. x gets the the address of y

Pointer Dereferencing If you have a pointer-to-type you can dereference the pointer to access the thing that it points to. The dereference operator is the * operator. The dereference operator can be used in a type declaration also... and it modifies the type.

Pointer Dereferencing int y; int *x; x = &y; *x = 42; let y be an int. let x be of a pointer that dereferences to an int. x gets the address of y. the int that is pointed-to by x gets 42.

Structures A collection of other types, packed together into a bigger type. Usually called t_something

Structures typedef struct { int a; int b; } t_twoints; define a type called t_twoints consisting of an int called a followed by an int called b...

Accessing Structure Elements t_twoints x; int y; x.a = 1; x.b = 1; member a in x gets 1 member b in x gets 2

Structure Assignment t_twoints x; t_twoints y; x.a = 1; x.b = 1; y = x member a in x gets 1 member b in x gets 2 y gets x

Pointer to a Structure int sum_twoints(t_twoints *y) { } let sum_twoints be a function that returns an int given a pointer-to a t_twoints called y

Pointer to a Structure int sum_twoints(t_twoints *y) { return y->a + y->b; } return the sum of a in the t_twoints pointed-to by y and b in the t_twoints pointed-to by y

Pointer to a Structure t_twoints x; int y; x.a = 1; x.b = 1; y = sum_twoints(&x); y gets the result of sum_twoints applied to the thing pointed-to by the address-of x

Dereferencing with Structures y->a is the same as (*y).a typedef struct twoints { int a; int b; } t_twoints; t_twoints y; y.a = 42; y.b = 43; t_twoints* y; y = (t_twoints*)malloc(sizeof(t_twoints)); y->a = 42; y->b = 43;

Memory Address 1 2 3 4 5 6 7... Contents 0 0 0 42 0 0 0 43

Memory containing a 4-byte integer Address Contents 1 2 3 4 5 6 7... 1st byte 2nd byte 3rd byte 4th byte sizeof(int) == 4 byte means number from 0-255

What is a pointer really? A reference is the memory address of a thing stored in memory. A reference cannot be changed. A pointer is a reference stored in memory. A pointer can be changed to the value of a reference to another thing (or nothing, also called a null pointer )

Memory Address Contents 1 2 3 4 5 6 7... 0 0 0 5 int *x; x = 5;

De-referencing * is the the de-referencing operator It is a unary operator It appears before the thing being dereferenced. (*x) is the value of the thing that x points to.

Memory Address Contents 1 2 3 4 5 6 7... 0 0 0 5 0 0 0 42 int *x; x = 5; *x = 42;

References & gets the address of something. Its also a unary prefix operator.

Setting a Pointer to a Thing Address Contents x int y; int *x; y 42 x = &y; *x = 42;

Huh? int y1; int y2; int *x; x = &y1; &y2 = x; // OK // Compiler error, // &y1 is not an lvalue

Pointer Arithmetic Suppose two things of the same type are located at sequential positions in memory: Let x point to the first one. x + 1 points to the second one.

Pointer Arithmetic int y1; int y2; int *x; x = &y1; *x = 42; *(x+1) = 43;

Pointer Incrementing int y1; int y2; int *x; x = &y1; *x = 42; x++; *x = 43;

Pointer types The actual memory address of x + 1 depends on the sizeof the pointed-to-type So, the compiler needs you to say what sort of thing is being pointed-to so it can figure this out. We can also use this to make arrays of things.

Pointers vs References They are the same thing, but... You can dereference a pointer You can dereference a reference You can assign an reference to a pointer You can assign a pointer to a pointer (or, increment it, decrement it, etc) You cannot assign anything to a reference

Arrays Lots of things of the same type The length of an array is fixed. It cannot be changed. Ever. In spite of this fact, the program has no idea how big your array is, and will do stupid things (like crashing) if you attempt to read or write to positions beyond the end of the array.

Array Indexing int y[2]; y[0] = 42; y[1] = 43;

Array Indexing Equivalent in Pointers int y[2]; *(y+0) = 42; *(y+1) = 43;

Even more Confusing Stuff int y[2]; int *x; x = &(y[0]); *x = 42; x = &(y[1]); *x = 43; y[0] dereferences the first element of y. Then we get a reference using &, assign it to x, dereference x, and assign the contents of that memory slot to the number 42.

Array Iterators Address Contents x int y[2]; int *x; y 42 x = y; *x = 42;

Array Iterators Address Contents x int y[2]; int *x; x = y; *x = 42; y 42 43 x++; *x = 43;

2D Arrays and Pointer to a Pointer Address Contents x int y[2][2]; int **x; x = y; **x = 42; y 42

Where Memory Comes From The Heap: Where globally allocated variables live Automatically reclaimed when program exits Where dynamically allocated memory comes from (using malloc or equivalent) Manually reclaimed using free (if you forget then its a memory leak )

Where Memory Comes From The Stack Where local variables live (declared in the scope of a function) Automatically reclaimed when the function returns

Dynamic Allocation void *malloc(size_t size); int *y; y = (int*)malloc(sizeof(int) * 2); y[0] = 42; y[1] = 43; free(y); Casting a pointer to a known type!

Dynamic Allocation, Notes malloc() is a system call Usually malloc is very fast, but it might take a long time to return (e.g. when swapping to disk is necessary). malloc could return NULL if it fails to obtain the requested number of bytes.

Preprocessor Directives #include somefile.h #define FOOBAR 1 #ifdef, #endif, #ifndef, #assert...

Macros Macros are ALLCAPS by convention, but not necessarily so. #define FOOBAR 3 now FOOBAR is replaced with its definition everywhere in the code. Macros can be sort of like functions #define FOOBAR(x) (x + 3) This should only be used when absolutely necessary (try use C99 + inline instead)

Compilation Explained Source Code (.c and.h files...) Preprocessor Compiler Object files (.o) Libraries Linker Executable or Library

Debugging Compilation: Tips Bad executable or Cannot load bundle executable The final product is messed up (bad meta data, unsupported processor target, etc)

Debugging Compilation: Tips Unresolved symbol foobar You probably used a function, foobar, from a library or another object file, but that library wasnʼt present during the linking stage.

Debugging Compilation: Tips Syntax error line XXX Compiler canʼt understand what you are doing. Look for the problem near the error with the LOWEST line number (many of the subsequent errors are probably bogus).

Debugging Compilation: Tips Syntax error line XXX but you really, really, really canʼt see anything wrong. Are you using a MACRO???

Debugging Compilation: Tips Cannot find file ʻfoobar.hʼ You have included a file, e.g. #include foobar.h But that file isnʼt in the current directory, and its not in the include file search path for the compiler. (-I) Similar problem but the missing file is a library Check library search path (-l)

Compiler Options Optimization level: -O1: some optimization -ffast-math: do floating point math fast, but might be less accurate (also in -O3). Target Platform -march=(...) what CPU instruction set do you want to support? Options vary greatly by compiler...

SEGFAULT Virtual memory means that addresses do not point directly to physical memory. Protected memory means the operating system knows which addresses are valid for your program ( segment ). If you attempt to use an invalid address then you get a segmentation fault.

SEGFAULT: Typical causes Attempting to dereference a pointer that hasnʼt been initialized Attempting to access item in an array that is past the end of the array Trying to use a pointer after its memory has been reclaimed (via free or return)

More Info... http://www.c-faq.com/ http://cprogramming.com/ man pages Various books (amazon, oʼreilly, etc)