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

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

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

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

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

PRINCIPLES OF OPERATING SYSTEMS

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

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

Pointers, Dynamic Data, and Reference Types

Class Information ANNOUCEMENTS

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

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

Lectures 5-6: Introduction to C

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

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

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

Kurt Schmidt. October 30, 2018

Lectures 5-6: Introduction to C

CSC 1600 Memory Layout for Unix Processes"

CS 61c: Great Ideas in Computer Architecture

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

A brief introduction to C programming for Java programmers

Dynamic memory allocation (malloc)

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

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

Intermediate Programming, Spring 2017*

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

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

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

Short Notes of CS201

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

Project 1. Soumya Basu. Department of Computer Science Cornell University February 5, 2016


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

CS201 - Introduction to Programming Glossary By

COMP 2355 Introduction to Systems Programming

Structures and Pointers

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

Programming in C - Part 2

CS349/SE382 A1 C Programming Tutorial

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

EL2310 Scientific Programming

CSC C69: OPERATING SYSTEMS

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

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

CS61C : Machine Structures

CS61C : Machine Structures

Lecture 2: C Programm

CS 11 C track: lecture 5

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

377 Student Guide to C++

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

COMP 2355 Introduction to Systems Programming

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

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

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

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

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

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

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

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

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

CSCI 171 Chapter Outlines

Recitation: Cache Lab & C

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

[0569] p 0318 garbage

Understanding Pointers

POINTER AND ARRAY SUNU WIBIRAMA

Quick review pointer basics (KR ch )

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

High Performance Programming Programming in C part 1

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

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

Procedures, Parameters, Values and Variables. Steven R. Bagley

EL2310 Scientific Programming

Memory Corruption 101 From Primitives to Exploit

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

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

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

Heap Arrays and Linked Lists. Steven R. Bagley

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

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

EL2310 Scientific Programming

CA31-1K DIS. Pointers. TA: You Lu

Lecture 2, September 4

EMBEDDED SYSTEMS PROGRAMMING Language Basics

CS 61c: Great Ideas in Computer Architecture

Arrays and Pointers in C. Alan L. Cox

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Arrays and Memory Management

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

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

Review of the C Programming Language for Principles of Operating Systems

ME964 High Performance Computing for Engineering Applications

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Lecture 3: C Programm

Quiz 0 Review Session. October 13th, 2014

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

Transcription:

Introduction to C Geared toward programmers Sean Ogden Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Ayush Dubey Cornell CS 4411, August 30, 2013

Administrative Information Outline 1 Administrative Information 2 Why C? 3 Pointers and Memory Management 4 Program Structure and Style 5 Concluding Remarks

Administrative Information Administrative Information Course Staff: same as CS 4410 (cs4410staff@systems.cs.cornell.edu) Office Hours On course webpage Immediately after lecture Lectures will rotate between TAs Keep checking CS 4411 webpage for announcements!

Administrative Information More Administrative Information 6 projects, 90% of your grade per-project weight not yet decided 10% of your grade from flexible components participation in class and discussions helping TAs identify errors... and lots of other opportunities! Strictly 2 members per project team member swaps are allowed between projects but inform course staff first also inform us if you or your teammate plans to drop the course!

Why C? Outline 1 Administrative Information 2 Why C? 3 Pointers and Memory Management 4 Program Structure and Style 5 Concluding Remarks

Why C? Predictability No unintended memory allocations. Control of layout of structures in memory. Simple syntax makes determining behavior easy.

Why C? Portability Most operating systems have a C compiler available...... (partially) because most operating systems are written in C. Linux, {Free,Open,Net,Dragonfly}BSD, Minix, XNU

Why C? Power Direct manipulation of control flow. Complex datastructure creation. Assembly is just a step away.

Introduction to C Why C? But great power can corrupt... which will it be, the stack or the heap?

Why C? Goals for today Provide a quick primer for using/learning C. Warn you of pitfalls related to C programming. Practice reading/writing C.

Outline 1 Administrative Information 2 Why C? 3 Pointers and Memory Management 4 Program Structure and Style 5 Concluding Remarks

Hello World #include <stdio.h> int main(int argc, char* argv[]) { printf("hello World!\n"); }

Try it out Install Microsoft SDK Set environment variables (path,include) to incorporate bin and include folders of Microsoft SDK Create hello.c. In a command prompt run: cl.exe hello.c Now run the hello.exe binary. If cl.exe complains about missing DLLs or library include paths, run vcvars32.bat or fetch it from the course webpage

The Programmer s Responsibilities Memory maintenance (no automatic garbage collection here). Error handling (no exceptions here).

Control flow Data types Operators Preprocessor

Control Flow if (x) { } else { } for (pre(); loop_invariant(); post()) { } while (x) { } do { } while (x); switch (x) { case 0: break; default: act(); }

Operators Arithmetic: +, -, *, /, % Relational: <, >, <=, >=, ==,!= Logical: &&,,!,?: Bitwise: &,, ˆ,!, «,»

Primitives Integer types: char : character, always one byte. int, short, long : integers of different sizes. Optional prefixes signed or unsigned. Floating point types: float : single-precision floating point. double : double-precision floating point. No booleans: 0 false 0 true

Sample Primitive Declarations char a = A ; char b = 65; char c = 0x41; int i = -2343234; unsigned int ui = 4294967295; unsigned int uj = ((long) 1 << 32) - 1; unsigned int uk = -1; float pi = 3.14; double long_pi = 0.31415e+1;

Enums enum months { JANUARY, FEBRUARY, MARCH }; enum days { SUNDAY, TUESDAY = 2, WEDNESDAY }; Values are consecutive integers starting from zero. Explicitly assigning a value causes the sequence to continue from that value (e.g., WEDNESDAY == 3).

Preprocessor Inclusion of other files: #include <header.h> Definition of constants: #define HOURS_PER_DAY 24 Creation of macros: #define CELSIUS(F) ((F - 32) * 5/9)

Pointers and Memory Management Pointers hold memory addresses An int: int foo; Pointer to an int: int* ptr_foo; Pointer to a pointer to an int: int** ptr_foo;

Pointers and Memory Management Pointer operations Obtain the address of a variable: & Dereference a memory address: *

Pointers and Memory Management Pointer Example int x; int* ptr; /* ptr points to an undefined location */ ptr = &x; /* ptr now points to integer x */ *ptr = 3; /* integer pointed to by ptr is now 3 */

Pointers and Memory Management Pass by Value swap_value() only changes n1 and n2 within the local scope. void swap_value(int n1, int n2) { int temp; temp = n1; n1 = n2; n2 = temp; }

Pointers and Memory Management Pass by Reference swap_reference() changes the values at the memory locations pointed to by p1 and p2. void swap_reference(int* p1, int* p2) { int temp; temp = *p1; *p1 = *p2; *p2 = temp; }

Pointers and Memory Management Function Pointers int inc(int i) { return i + 1; } int dec(int i) { return i - 1; } int apply(int (*f)(int), int i) { return f(i); } int main(int argc, char* argv[]) { printf("++: %i\n", apply(inc, 10)); printf("--: %i\n", apply(dec, 10)); } return 0;

Pointers and Memory Management Heap Variables Allocate with malloc() and deallocate with free(). void* malloc(int) void free(void*) It is up to you to manage memory. Never calling free() leaks memory. Calling free() more than once will crash your program. Known as a double free bug, and is sometimes exploitable.

Pointers and Memory Management Malloc/Free Example int* ptr; /* pointer to an int */ /* allocate space to hold an int */ ptr = (int*) malloc(sizeof(int)); /* check if successful */ if (ptr == NULL) exit(1); *ptr = 4; /* store value 4 in the int */ printf("ptr: %p %d\n", ptr, *ptr); /* deallocate memory */ free(ptr);

Pointers and Memory Management Warning Dereferencing an un-initialized pointer can crash your program (or worse)! Consider initializing a pointer to NULL and checking before dereferencing. Some functions return NULL on error. Pay attention to the function specification! Check return values!

Pointers and Memory Management Arrays and Strings Arrays for (i = 0; i < 10; ++i) { A[i] = i * i; } Strings char name[] = "CS4410"; name[5] = 1 ; Functions to operate on strings in string.h. strncpy, strncmp, strncat, strstr, strchr

Program Structure and Style Outline 1 Administrative Information 2 Why C? 3 Pointers and Memory Management 4 Program Structure and Style 5 Concluding Remarks

Program Structure and Style Structures struct list_elem { int data; struct list_elem* next; }; int main(int argc, char* argv[]) { struct list_elem le = { 10, NULL }; le.data = 20; } return 0;

Program Structure and Style Typedefs Create an alias for a type. Syntax: typedef type alias Use it like any primitive: list_elem_t le; typedef struct list_elem { int data; struct list_elem* next; } list_elem_t;

Program Structure and Style Code Style Write comments where appropriate! Bad comment: /* print the value of x */ Good comment: /* take one process off the ready queue */ Create logically names constants and variables. Bad naming: struct lock mylock, lock1 Good naming: struct lock process_queue_lock Split large functions into smaller functions.

Concluding Remarks Outline 1 Administrative Information 2 Why C? 3 Pointers and Memory Management 4 Program Structure and Style 5 Concluding Remarks

Concluding Remarks Summary C is a great language (especially for systems work). Save yourself some trouble: Initialize variables before use. Don t return pointers to stack-based variables. Allocate and deallocate memory properly. Check return values. Use version control! keep track of changes, merging changes from all developers (check out SVN, CVS, Git etc.)

Concluding Remarks Some advice Start projects early! If you feel a problem is unclear or underdefined, seek clarification or make reasonable design assumptions. Don t put off questions if you have any. Don t think of this course as course staff vs students, we are all here to learn, TAs included.

Concluding Remarks Introduction to C Sean Ogden sean @ cs August 30, 2013