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

Similar documents
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

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, 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

Class Information ANNOUCEMENTS

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

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

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS


Dynamic memory allocation (malloc)

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

Lectures 5-6: Introduction to C

CSC 1600 Memory Layout for Unix Processes"

Intermediate Programming, Spring 2017*

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

Kurt Schmidt. October 30, 2018

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

Structures and Pointers

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

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

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

EMBEDDED SYSTEMS PROGRAMMING Language Basics

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

EL2310 Scientific Programming

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Dynamic Memory Allocation and Command-line Arguments

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

Understanding Pointers

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

A brief introduction to C programming for Java programmers

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

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

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

CS 61c: Great Ideas in Computer Architecture

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

[0569] p 0318 garbage

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

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

EMBEDDED SYSTEMS PROGRAMMING Language Basics

CS 11 C track: lecture 5

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

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

Quick review pointer basics (KR ch )

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

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

Lecture 07 Debugging Programs with GDB

Recitation: C Review. TA s 20 Feb 2017

Processes. Johan Montelius KTH

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

CS61C : Machine Structures

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

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

Heap Arrays and Linked Lists. Steven R. Bagley

A process. the stack

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

EL2310 Scientific Programming

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

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

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

CS201 Latest Solved MCQs

CS349/SE382 A1 C Programming Tutorial

Common Misunderstandings from Exam 1 Material

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Lecture 2, September 4

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

Memory (Stack and Heap)

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

CSC C69: OPERATING SYSTEMS

377 Student Guide to C++

Heap Arrays. Steven R. Bagley

POINTER AND ARRAY SUNU WIBIRAMA

Lecture 3: C Programm

Review of the C Programming Language for Principles of Operating Systems

Memory Corruption 101 From Primitives to Exploit

ME964 High Performance Computing for Engineering Applications

COMP 2355 Introduction to Systems Programming

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

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

Lecture 2: C Programm

EL2310 Scientific Programming

COMP 2355 Introduction to Systems Programming

Chapter IV Introduction to C for Java programmers

Quiz 0 Review Session. October 13th, 2014

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Arrays and Pointers in C. Alan L. Cox

Memory Allocation in C

CSCI 171 Chapter Outlines

High Performance Programming Programming in C part 1

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

CS61C : Machine Structures

a data type is Types

Transcription:

Introduction to C Geared toward programmers Zhiyuan Teo Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Cornell CS 4411, August 26, 2011

1 Administrative Information 2 Why C? 3 A Quick Example 4 Programmer s Responsibilities 5 Pointers and Memory Management 6 Program Structure

Administrative Information Administrative Information Course Staff Zhiyuan "Z" Teo (zteo@cs) Ki Suh Lee (kslee@cs) Office Hours - 361 Upson Hall Monday 3.20pm - 4.25pm (Zhiyuan) Wednesday 3.20pm - 4.25pm (Ki Suh) Immediately after lecture Or by appointment Lectures will rotate between TAs. No independent course webpage, so check the 4410 site for announcements.

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

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

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, Windows

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

Why C? Power Direct, unprotected control over the system hardware. Complex data structure 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.

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

A Quick Example Try it out Create hello.c. In a VS2008 command prompt run: cl hello.c Now run the hello.exe binary. If cl.exe complains about missing DLLs or library include paths, run vsvars32.bat first from the common7\tools folder in the VS2008 installation directory. or fetch it from the course webpage

A Quick Example Learning a new language Languages are largely the same. Notice the similarities. Control structures (loops, conditionals, etc.) Data types (int, char, classes, etc) Embrace diversity. Play on a language s strengths. Don t use a square peg for a round hole.

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

Control flow Operators Data Types Preprocessor

Control Flow if (x) { } else if (y) { } 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, typically 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 standard library files: #include <header.h> Inclusion from local directory: #include "myfile.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 Global Variables Declared outside all functions. Space allocated before execution. Space deallocated at program exit. Learn the meanings of static and extern (storage class modifiers).

Pointers and Memory Management Local Variables Declared at the start of the function. Space is allocated on the stack. Initialized before function execution. Deallocated when leaving the function scope. Also known as deleting the stack frame.

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 - null-terminated arrays! char name[] = "CS4410"; name[5] = 1 ; Functions to operate on strings in string.h. strncpy, strncmp, strncat, strstr, strchr

Program Structure Functions Arguments can be passed: by value: a copy of the parameter is passed into the function. by reference: a pointer is passed into the function. Return values are also by value or by reference.

Program Structure 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; }

Program Structure 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; }