C Tutorial Ross Shaull cs146a 2011-09-21. Why C Standard systems language – Historical reasons (OS have historically been written in C, so libraries written.

Slides:



Advertisements
Similar presentations
Topic Reviews For Unit ET156 – Introduction to C Programming Topic Reviews For Unit
Advertisements

What Is Java? The name Java is a trademark of Sun Microsystems
Introduction to C Programming
Pointers.
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Malloc Recitation By sseshadr. Agenda Macros in C Pointer declarations Casting and Pointer Arithmetic Malloc.
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Introduction to Programming G51PRG University of Nottingham Revision 1
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Sockets Tutorial Ross Shaull cs146a What we imagine Network request… response… The packets that comprise your request are orderly.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 Today’s lecture  Last lecture we started talking about control flow in MIPS (branches)  Finish up control-flow (branches) in MIPS —if/then —loops —case/switch.
Ch. 8 Functions.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Memory Layout C and Data Structures Baojian Hua
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Copyright 2013 – Noah Mendelsohn Process Memory Noah Mendelsohn Tufts University Web:
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
IT253: Computer Organization Lecture 4: Instruction Set Architecture Tonga Institute of Higher Education.
Programming With C.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Agenda Attack Lab C Exercises C Conventions C Debugging
C Lab 1 Introduction to C. Basics of C Developed by Dennis Ritchie in the 1970s. Maps very easily to machine instructions. Even allows inline assembly!
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
C LANGUAGE Characteristics of C · Small size
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Windows Programming Lecture 03. Pointers and Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
A bit of C programming Lecture 3 Uli Raich.
Process Memory COMP 40: Machine Structure and
ENEE150 Discussion 07 Section 0101 Adam Wang.
CSE 303 Concepts and Tools for Software Development
C Basics.
Memory Allocation CS 217.
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Topics Compilation Using the gcc Compiler
CSE 303 Concepts and Tools for Software Development
Introduction to C CS 3410.
Presentation transcript:

C Tutorial Ross Shaull cs146a

Why C Standard systems language – Historical reasons (OS have historically been written in C, so libraries written in C were the easiest to integrate and usually had performance advantage) Useful skill – C is still useful in the real world, both for interfacing with legacy systems and for producing performance- critical new code Builds character – You will learn about your OS and the tools used to develop your OS

Writing a C Program We'll use a text editor in this class I recommend Emacs You can use an IDE if you want

Compiling a C Program We'll use gcc from the command line in this tutorial We'll also learn a little about GNU Make (an age old tool to save you from typing stuff)

Hello World in C arguments to the program when it is executed serves same function as System.out.print in Java

Compiling helloworld

How did Make do that? Make knows how to compile simple C programs all by itself It figured out from `make helloworld` that I want to compile helloworld.c into a binary called helloworld It invoked gcc for me But we can make a Makefile ourselves and customize the behavior a bit

Things it was doing automatically

You can leave some things out

We can just customize CFLAGS

Is C Like Prog Lang X? Your basic Java skills (or any ALGOL-like programming language skills) will translate – variables, assignment, arithmetic – if statements and boolean expressions – while loops, for loops, do-while loops – functions and function parameters Some things are different – memory management feels very different from modern languages, and there is no garbage collector! – no OO – pointers! If you are used to higher order programming languages, you will miss those features in C, don't try to replicate them

Memory Linear array of "cells" Each cell stores a machine word (4 bytes in 32-bit machine, 8 bytes in 64-bit machine) addressvalue (byte)

Memory Machine code might contain an "immediate mode" store command to put the value 42 into the byte at address 3 A byte can represent 2 8 = 256 numbers (0 – 255) addressvalue (byte)

Memory In C we don't put memory addresses directly in our program text, but we can see the address of variables at runtime printf("%p\n", &var); addressvalue (byte)

Memory is on the stack or heap In Java, you get heap memory with new and the rest of variables are on the stack – This doesn't matter to you as the programmer In C, you get heap memory with malloc and you give it back with free Match your mallocs with frees or you will leak memory

Allocating Telling the compiler you need space on the stack for an integer: – int i; Telling the compiler you need space on the stack for a pointer to an integer: – int *ip; Telling the operating system at runtime that you need space on the heap for an integer: – ip = malloc(sizeof(int));

Allocating You should check for errors (always) – if((ip = malloc(sizeof(int))) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); }

Pointers are abstraction of memory addresses

But not the real memory virtual addressvalue (byte) addressvalue (byte) ……

But not the real memory virtual addressvalue (byte) addressvalue (byte) …… Virtual memory!

Memory abstraction We'll treat pointers as though they are pointers to real memory, because that's what the virtual memory abstraction gives us (the illusion that we own the machine) Just don't forget that we still have isolation, paging, and all the other good stuff we get from virtual memory

Types C is weakly typed You can cast any pointer to any other pointer – Feel free to try weird stuff like casting an integer to a string, the worst that will happen is segfault or bus error (because of isolation nothing will be harmed)

Types int double long char there's more…

Arrays Multiple cells next to each other int nums[10]; nums[0] = 42; nums[9] = 100; nums[10] = 1; // UH OH this is a bug These arrays contain garbage not zeros!!! The length is not stored with the array If you are making an array for convenience you can initialize it right away int nums[] = {1, 2, 4, 8, 16, 32, 64, 128}; These are on the stack. You can put arrays in the heap int *nums = malloc(10 * sizeof(int)); nums[0] = 42;

Strings Pointer to one or more characters char *s = malloc(20); char *s = malloc(20 * sizeof(char)); char s[20]; You can address strings like arrays: s[0] = 'a' By the way, strings in the text of your code are typically stored in the code section of the compiled binary

Strings "Strings" are arrays of chars Arrays don't carry their length around with them By convention, strings in C end with a NULL byte '\0' (called NULL-terminated strings) You can find the length of a NULL-terminated string by counting bytes until you find \0 That's what strlen does: – strlen(s) Only do this with strings you created because it's a place where you can get buffer overruns and segfaults

Structs Records, not objects (no methods) struct record_t { char name[255]; int age; }; It's name is "struct record_t" struct record_t record = {.name = "Bob",.age = 21}; struct record_t *recordp; recordp = malloc(sizeof(record_t)); I use typedef and a semi-idosyncratic style typedef struct record_t { char name[255]; int age; } RECORD; RECORD record;

C moves memory around efficiently

System Calls We'll use them a lot They are special addresses (set up when the OS is starting up) that trigger a switch to kernel mode, and then jump to a special function If your OS can do it, you can ask your OS to do it from C (in higher level languages the features may not be available, because somebody has to write that code)

System Calls (although actually we'll be using very standard syscalls that are available in virtually every programming language)

System Calls printf – yes read file – yes write file – yes malloc – yes memcpy – no! free – yes strlen – no! starting a (kernel) thread – yes!

For your project compiling (gcc and Make) basic programming stuff basic pointers – console output (printf) sockets (up next) threads – we assume you have seen thread before – we will give you a recipe for starting and joining threads in C using pthreads

By the way You'll want to use multiple files to make it easier to understand your code and to start to visualize how it is modularized In C we have header files and source files – header files define prototypes (names and signatures of functions) – source files implement those prototypes – we include the header file – we'll give you an example