just a ((somewhat) safer) dialect.

Size: px
Start display at page:

Download "just a ((somewhat) safer) dialect."

Transcription

1 Intro_to_C Page 1 Intro to C Tuesday, September 07, :30 PM C was developed specifically for writing operating systems Low level of abstraction. "Just above machine language." Direct access to the machine when desired. Highly efficient. Has two predecessors and one successor: A: assembler. B: block program structure (but no block data). C: block structure and block data. (D: adds memory descriptors) C++ is not "more powerful" than C; it is just a ((somewhat) safer) dialect.

2 Intro_to_C Page 2 An old adage: Tuesday, September 15, :27 PM C programmers know the cost of everything but the value of nothing. Lisp programmers know the value of everything but the cost of nothing.

3 Intro_to_C Page 3 Speed and danger Tuesday, September 07, :30 PM Speed and danger C is an "unsafe" language. No bounds checking on arrays No type checking during subroutine calls. Pointers (at whatever cost) Computed gotos (using function pointers). Why? Speed is more important than safety.

4 Intro_to_C Page 4 C design principles Tuesday, September 15, :40 PM C design principles Trust the programmer. Speed over correctness. No run-time checking. Information hiding by not exposing structure.

5 Intro_to_C Page 5 A typical C program Tuesday, September 15, :45 PM #include <stdio.h> int main(int argc, char **argv, char **envp) { printf("hello\n"); exit(0); }

6 Intro_to_C Page 6 Annotation of the program Thursday, September 09, :13 PM #include <stdio.h> /* include a header file "stdio.h" containing reusable declarations */ int main(int argc, char **argv, char **envp) /* program is always called "main". argc is number of arguments on the command line, argv is an array of arguments (as strings). envp is an array of environment variables. */ { printf("hello\n"); /* call the library function "printf" */ } exit(0); /* stop running with "success" code: system call! */

7 Intro_to_C Page 7 Compiling a C program Tuesday, September 15, :43 PM To compile a C program "hello.c", on comp111 gcc -g -c hello.c # creates hello.o, a relocatable object file gcc -o hello hello.o # creates hello from hello.o./hello # run the program Or, alternatively gcc -g hello.c # means gcc -o a.out -g hello.c

8 Intro_to_C Page 8 Printing Tuesday, September 15, :59 PM printf("format", arguments ) is general printing statement. "format" represents a string, which is an array of characters. "string" a string 's' a character "format" can contain: %d: print an integer %f: print a floating point number %s: print a string %%: print a percent character(!) \n: print a carriage return printf("one is %d\n",1); => "one is 1\n" printf("two point zero is %f\n",2.0); => "two point zero is 2.0" printf("these are %d, %f\n", 1, 2.0);

9 Intro_to_C Page 9 Printing one's arguments Tuesday, September 15, :19 PM #include <stdio.h> int main(int argc, char **argv, char **envp) { int i; printf("arguments\n"); for (i=0; i<argc; i++) printf("argument %d is '%s'\n",i,argv[i]); printf("environment\n"); for (i=0; envp[i]!=null; i++) printf( "environment variable %d is '%s'\n",i,envp[i]); } argv[0]-argv[argc-1] are the command-line arguments. envp[0]-... are the environment variables. envp[i]==0 means stop listing!

10 Intro_to_C Page 10 The linux manual pages Tuesday, September 15, :03 PM printf is not part of C. Instead, it is a library function that is documented in the linux manual pages. From the linux command line, type man printf or man 3 printf # check in section 3: the C library to learn about it.

11 Intro_to_C Page 11 Another simple program Tuesday, September 15, :28 PM #include <stdio.h> int main(int argc, char **argv, char **envp) { int pid = fork(); /* a system call */ if (pid!=0) { printf("i'm the parent\n"); sleep(5); /* library */ printf("killing pid %d\n", pid); kill(pid,9); /* kill my child! system call */ printf("killed pid %d\n", pid); } else { /* I'm the child: wait to die! */ int count = 0; printf("i'm the child!\n"); while(1) { sleep(1); ++count; printf("i've been around for %d seconds\n",count); } } exit(0); }

12 Intro_to_C Page 12 Explanation of the program Tuesday, September 15, :28 PM Explanation of the program fork(): split into two processes. sleep(5): sleep for five seconds. kill(pid,9): send a kill signal (9) to the process numbered pid. For more details man 2 kill man 2 fork man 3 sleep kill is a system call: these are documented in section 2 of the manual. Note that man 1 kill or man kill describes the kill command, which is different.

13 Intro_to_C Page 13 General caveats Tuesday, September 15, :42 PM There are three things to know in programming in C: the language C itself how to use the available system calls (man 2 x) how to use the available library functions (man 3 x) Using a function read the man page. #include the appropriate headers (e.g., <stdio.h> for printf) Call the function with the appropriate arguments (e.g., printf("%d\n",i))

14 Intro_to_C Page 14 Watch out Tuesday, September 15, :45 PM C is not type-safe Note that printf("%f",2.1); prints what you would expect, while printf("%d",2.1); prints (predictable but useless) garbage. Why? The second tries to print (the first half of) a double-precision number as an integer, which doesn't work the way one might expect!

15 Intro_to_C Page 15 Lack of polymorphism Tuesday, September 14, :00 PM C is not polymorphic foo(int) and foo(float) are the same function. You must distinguish between argument types!

16 Watch out: logical equivalence Tuesday, September 15, :14 PM Note that an expert C programmer is always conscious of speed of execution. Note that while(x!=0) { printf("x is %d\n",x); x=x-1; } means exactly the same thing as while(x) { printf("x is %d\n", x); --x } but the second is a bit faster. An expert would not write the first version! You will commonly see very terse C in OS code. One can: test for whether a pointer is NULL (0) by treating it as boolean! test for whether an integer is 0 by treating it as boolean! etc. const char *p; p = "hello\n"; const char *q; q=p; while (*q) { printf("%c",*q); q++; } The optimizer debate: "New school" programmers contend that this is handled by the optimizer. "Old school" programmers are more explicit and do not rely upon that. Intro_to_C Page 16

17 Intro_to_C Page 17 Value of a statement Tuesday, September 15, :22 PM Each statement has a value. x=1 has value 1 x=y+z has the value of x after the assignment. ++x has the value of x after increment x++ has the value of x before increment E.g. x=1 y=(x++) sets x to 2 and y to 1! Reason for this: loop optimization. Consider: x=0; while(x<20) a[x++]=0; This sets elements a[0] to a[19] to 0, but stops before element 20. Equivalent to: x=0; while (x<20) { a[x]=0; ++x; } but the former avoids a register reload.

18 Intro_to_C Page 18 Structures Thursday, September 09, :13 PM C structures Concatenation of basic types Example: struct foo { int i; double d; } s; ANSI standard layout: "Lay out structure by ascending address, but align each type on a multiple of its length."

19 Intro_to_C Page 19 Addressing structures Tuesday, September 15, :29 PM struct foo x; x.i=4; x.d=5.6;

20 Intro_to_C Page 20 C has no classes Tuesday, September 13, :56 PM C has no classes Structs: the data part of a class. The function part requires polymorphism, which C doesn't have. You will see OS programmers "growing their own classes". Ex: struct foo { } ; struct foo *foo_create(); void foo_destroy(struct foo *); void foo_set(struct foo *, int i);.

21 Intro_to_C Page 21 Unions Thursday, September 09, :13 PM Unions Allow one to create aliases for the same kind of memory. Example union g { int i; double d; } t; t.i contains the first eight bytes of t.d Very often, in programming an OS, we need to decide on the fly what kind of data a block contains. Unions allow us to define things that can represent multiple kinds of things, very efficiently. struct discriminated_union { enum {WROTE_I, WROTE_D} discriminant; }; union g { int i; double d; } t;

22 The prefix rule Thursday, September 09, :13 PM The Prefix Rule If one structure is a prefix of another, the two structures are organized in memory identically for the common prefix. Example: struct foo { int i; double d; } s; struct foo2 { int i; double d; float f; } u; Intro_to_C Page 22

23 Intro_to_C Page 23 Information hiding Thursday, September 09, :13 PM C Information Hiding If you want to hide something about a struct, give the user a pointer to a prefix of the struct; leave other data unavailable. Example: struct foo2 h; struct foo *j = (struct foo *) &h; return j; Unfortunately, I can get around this: If j is as above, then *((float *)((double *)(((int *)j)+2))+1)) refers to the element we tried to hide.

24 Basics of pointers Thursday, September 09, :36 PM Pointers Look in memory like integers Job: identify other memory. For an object o, &o is the address of o. For a pointer p, *p is the thing pointed to by p. Basic pointer principles p = q means "make p point where q points". p = &o means "make p point where o lives". (After this, *p is an alias for o) Intro_to_C Page 24

25 Intro_to_C Page 25 Pointers and references Thursday, September 15, :15 PM Pointers and references In C++ and Java, there is the concept of a "reference" A reference: Has only one type. Can only refer to a single thing. Resolves the ambiguity between *p and p[] A pointer: Just tells where something is. Can refer to memory without a type (void *) Can be treated as having several types (via pointer casts)

26 Intro_to_C Page 26 Pointer diagramming Thursday, September 16, :57 PM Diagram variables as boxes int k; Diagram variable pointers as pointing nowhere: int *p=null; pointing to a thing: int *q=&k; Diagram arrays as linear arrangements of boxes: int a[5]; Diagram structures as linear arrangements of things (with possible holes) struct foo { int k; double d; } f; (int *q = &k; is shorthand for int *q; q=&k; )

27 Intro_to_C Page 27 Lvalues and Rvalues Thursday, September 16, :57 PM An lvalue is something that can be on the left-hand side of = An rvalue is something that can be on the right-hand side of = Normal pointers (int *) are lvalues Array names are rvalues and not lvalues. int a[5]; // a is of type "int * const" ("a" can't be set) You can say *a=7, or a[5]=9, but not a=&q; Compare with const int *k; k=&i; // can write k=, cannot write *k=

28 Pointer rules Thursday, September 09, :36 PM Pointer rules: if a is a pointer or array: *a: thing pointed to by a. a+1: pointer to thing one cell up from a (same size as *a) *(a+1): thing one cell up from a (same size as *a) a-1: pointer to thing one cell down from a. *(a-1): thing one cell down from a. a[i] is defined as *(a+i) (also written as i[a]) a->b is defined as (*a).b For a pointer a, &*a=a, For a thing b, *&b=b. Array references cannot -- intrinsically -- be bounds checked. Intro_to_C Page 28

29 Intro_to_C Page 29 End of lecture on Wednesday, September 10, :02 PM

30 Intro_to_C Page 30 Arrays and pointers example Thursday, September 16, :01 PM

31 Intro_to_C Page 31 Pointer caveats Thursday, September 09, :36 PM Caveats: for p, q pointers; i,j integers: p+i=pointer, p-i=pointer, p-q=integer (distance between p and q), p+q is meaningless One can set a pointer to anything provided that one doesn't access it: p=null; // #define NULL 0 *p=2; // guaranteed seg fault.

32 Intro_to_C Page 32 Basic pointer casts Thursday, September 09, :36 PM A pointer cast determines what kind of data a pointer refers to: If p is a pointer, (int *)p is another pointer that points to an array of ints. (struct foo *)p is another pointer that points to an array of things of type struct foo. Pointer casts are a semantic operation The pointer doesn't change. It is simply thought of in a different way. Operations on the pointer change meanings! A pointer cast Redefines pointer reference (to a potentially larger or smaller thing). Redefines pointer addition (to increment or decrement by the size of the thing).

33 Intro_to_C Page 33 Pointer casts Thursday, September 09, :36 PM Why pointer casts are important The operating system, unlike a user program, has to deal with data whose type it does not know. Often, a block of memory can have multiple meanings. Basic strategy: treat unknown types as void, or void *, and then later, cast them to types they are. More generally, Whenever it is necessary to use a block of memory in a new way, can cast a pointer to it to the appropriate type. This is the root of how dynamic memory allocation is done. In C++, p = new x; creates a new instance of the object x In C, there is no "new", instead, p = (int *)malloc(sizeof(int)*5) creates an array of 5 ints. malloc returns a pointer of type "void *": type unknown.

34 Intro_to_C Page 34 Unions and casts Thursday, September 09, :36 PM union { struct foo s; int p[4]; } u; What a pointer cast does is to treat the data at the pointer like a union.

35 Intro_to_C Page 35 dynamic memory allocation Thursday, September 15, :29 PM Dynamic memory allocation: allows an application to get new memory to use for its own purposes. Global variable Arbitrary size Arbitrary lifetime malloc grants access, free revokes it.

36 Intro_to_C Page 36 C versus C++ Thursday, September 16, :48 PM C C++ Java int *p=(int *)malloc(10 *sizeof(int)); int *p=new int[10]; int p[] = new int[10]; free(p); delete p; No equivalent new calls malloc! delete calls free!

37 Intro_to_C Page 37 Malloc caveats Thursday, September 09, :47 PM Malloc caveats Data returned is a pointer to storage. Data is uninitialized; contains seemingly random values (impractical to predict in advance) No constructors; you manually initialize data. Everything is done by changing type of data after malloc (by pointer casts) Why no initialization? Many data structures don't need to be initialized (Example: large hash tables) Without initialization, malloc executes in O(1) in most cases (constant time) With initialization, it executes in O(n) (n=number of bytes) Why bother to initialize if you don't always need it? Common practice: encapsulate initialization struct foo { int i; double d; } struct foo *foo_create() { struct foo *m = (struct foo *) malloc(sizeof(struct foo)); m->i=0; m->d=0;

38 Intro_to_C Page 38 return m; } void foo_delete(struct foo *f) { free(f); } main() { struct foo *f = foo_create(); foo_delete(f); }

39 Intro_to_C Page 39 Using free() Thursday, September 09, :47 PM Must explicitly free() storage so it can be reused. free(p) does not change p! Subsequent allocations can reuse memory. This can cause a pointer alias and havoc can ensue. Typical horror story: int *p=(int *)malloc(sizeof(int)); free(p); int *q=(int *)malloc(sizeof(int)); // reuse p's data! *p=5; // change *q!

40 Intro_to_C Page 40 The big deal Thursday, September 17, :14 PM When an OS gives your process memory to use, it does not know the types you assign to it. That information is not just unknown, but also unknowable. C is not reflective (unlike Java)!

just a ((somewhat) safer) dialect.

just a ((somewhat) safer) dialect. Intro_to_C Page 1 Intro to C Tuesday, September 07, 2004 5:30 PM C was developed specifically for writing operating systems Low level of abstraction. "Just above machine language." Direct access to the

More information

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

So far, system calls have had easy syntax. Integer, character string, and structure arguments. Pointers Page 1 So far, system calls have had easy syntax Wednesday, September 30, 2015 10:45 AM Integer, character string, and structure arguments. But this is not always true. Today, we begin to explore

More information

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

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

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

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

0x0d2C May your signals all trap May your references be bounded All memory aligned Floats to ints round. remember... Types Page 1 "ode to C" Monday, September 18, 2006 4:09 PM 0x0d2C ------ May your signals all trap May your references be bounded All memory aligned Floats to ints round remember... Non -zero is true ++

More information

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

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Functions Similar to (static) methods in Java without the class: int f(int a, int

More information

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

CS 61C: Great Ideas in Computer Architecture Introduction to C CS 61C: Great Ideas in Computer Architecture Introduction to C Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/ 1 Agenda C vs. Java vs. Python Quick Start Introduction

More information

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

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

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

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers in C. Alan L. Cox Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including

More information

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

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture CS 61C: Great Ideas in Computer Architecture Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

ntroduction to C CS 2022: ntroduction to C nstructor: Hussam Abu-Libdeh (based on slides by Saikat Guha) Fall 2011, Lecture 1 ntroduction to C CS 2022, Fall 2011, Lecture 1 History of C Writing code in

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Supporting Class / C++ Lecture Notes

Supporting Class / C++ Lecture Notes Goal Supporting Class / C++ Lecture Notes You started with an understanding of how to write Java programs. This course is about explaining the path from Java to executing programs. We proceeded in a mostly

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

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

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

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

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( ) Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough

More information

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

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2 CMPT 125 Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance John Edgar 2 Edit or write your program Using a text editor like gedit Save program with

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

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

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

ELEC 377 C Programming Tutorial. ELEC Operating Systems

ELEC 377 C Programming Tutorial. ELEC Operating Systems ELE 377 Programming Tutorial Outline! Short Introduction! History & Memory Model of! ommon Errors I have seen over the years! Work through a linked list example on the board! - uses everything I talk about

More information

CSE 303 Lecture 8. Intro to C programming

CSE 303 Lecture 8. Intro to C programming CSE 303 Lecture 8 Intro to C programming read C Reference Manual pp. Ch. 1, 2.2-2.4, 2.6, 3.1, 5.1, 7.1-7.2, 7.5.1-7.5.4, 7.6-7.9, Ch. 8; Programming in C Ch. 1-6 slides created by Marty Stepp http://www.cs.washington.edu/303/

More information

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

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1 A Quick guide to C for Networks and Operating Systems

More information

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

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019 Hacking in C Pointers Radboud University, Nijmegen, The Netherlands Spring 2019 Allocation of multiple variables Consider the program main(){ char x; int i; short s; char y;... } What will the layout of

More information

Lectures 13 & 14. memory management

Lectures 13 & 14. memory management Lectures 13 & 14 Linked lists and memory management Courtesy of Prof. Garcia (UCB) CS61C L05 Introduction to C (pt 3) (1) Review Pointers and arrays are virtually same C knows how to increment pointers

More information

Programming. Data Structure

Programming. Data Structure Programming & Data Structure For Computer Science & Information Technology By www.thegateacademy.com Syllabus Syllabus for Programming and Data Structures Programming in C, Arrays, Stacks, Queues, Linked

More information

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

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

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

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

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

M.EC201 Programming language

M.EC201 Programming language Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2 The union Keyword The

More information

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

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Names, Scope, and Bindings

Names, Scope, and Bindings Names, Scope, and Bindings COMS W4115 Prof. Stephen A. Edwards Spring 2007 Columbia University Department of Computer Science What s In a Name? Name: way to refer to something else variables, functions,

More information

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. Refresher When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. i.e. char *ptr1 = malloc(1); ptr1 + 1; // adds 1 to pointer

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Memory Management 2007-06-28 Scott Beamer, Instructor iphone Comes out Tomorrow CS61C L4 C Memory Management (1) www.apple.com/iphone

More information

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1 F28HS2 Hardware-Software Interface Lecture 1: Programming in C 1 Introduction in this half of the course we will study: system level programming in C assembly language programming for the ARM processor

More information

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers! Arrays and Pointers (part 2) EECS 2031 22 October 2017 1 Be extra careful with pointers! Common errors: l Overruns and underruns Occurs when you reference a memory beyond what you allocated. l Uninitialized

More information

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

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

#include <stdio.h> int main() { printf (hello class\n); return 0; } C #include int main() printf ("hello class\n"); return 0; Working environment Linux, gcc We ll work with c9.io website, which works with ubuntu I recommend to install ubuntu too Also in tirgul

More information

Lecture 04 Introduction to pointers

Lecture 04 Introduction to pointers Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

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

C Introduction. Comparison w/ Java, Memory Model, and Pointers CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Pointers Pointers denote addresses in memory In C types, the * represents the use

More information

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy

More information

Memory Allocation. General Questions

Memory Allocation. General Questions General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char

More information

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

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers 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

More information

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

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011 Two s Complement Review CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part I) Instructor: Michael Greenbaum http://inst.eecs.berkeley.edu/~cs61c/su11 Suppose we had

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Introduction to C, Pointers June 24, 2014 Review of Last Lecture Six Great Ideas in Computer Architecture Number Representation Bits can represent anything! n bits can represent up to 2 n things Unsigned,

More information

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

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices. Memory and Addresses Memory is just a sequence of byte-sized storage devices. 1 The bytes are assigned numeric addresses, starting with zero, just like the indexing of the cells of an array. It is the

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

Memory, Data, & Addressing II CSE 351 Spring

Memory, Data, & Addressing II CSE 351 Spring Memory, Data, & Addressing II CSE 351 Spring 2018 http://xkcd.com/138/ Review Questions 1) If the word size of a machine is 64-bits, which of the following is usually true? (pick all that apply) a) 64

More information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C. Reading. goto Considered Harmful History Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

EMBEDDED SYSTEMS PROGRAMMING Language Basics

EMBEDDED SYSTEMS PROGRAMMING Language Basics EMBEDDED SYSTEMS PROGRAMMING 2014-15 Language Basics (PROGRAMMING) LANGUAGES "The tower of Babel" by Pieter Bruegel the Elder Kunsthistorisches Museum, Vienna ABOUT THE LANGUAGES C (1972) Designed to replace

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory.

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory. Memory Management Page 1 Memory Management Wednesday, October 27, 2004 4:54 AM Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory. Two kinds

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

My malloc: mylloc and mhysa. Johan Montelius HT2016

My malloc: mylloc and mhysa. Johan Montelius HT2016 1 Introduction My malloc: mylloc and mhysa Johan Montelius HT2016 So this is an experiment where we will implement our own malloc. We will not implement the world s fastest allocator, but it will work

More information

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

HW1 due Monday by 9:30am Assignment online, submission details to come inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am

More information

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

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1 Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic

More information

Section 2: Processes

Section 2: Processes September 7, 2016 Contents 1 Warmup 2 1.1 Hello World............................................ 2 2 Vocabulary 2 3 Problems 3 3.1 Forks................................................ 3 3.2 Stack Allocation.........................................

More information

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

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

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

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers Introduction to C Geared toward programmers Ayush Dubey Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Cornell CS 4411, August 31, 2012 Administrative Information Outline

More information

Heap Arrays. Steven R. Bagley

Heap Arrays. Steven R. Bagley Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

Arrays and Pointers (part 2) Be extra careful with pointers!

Arrays and Pointers (part 2) Be extra careful with pointers! Arrays and Pointers (part 2) CSE 2031 Fall 2011 23 October 2011 1 Be extra careful with pointers! Common errors: Overruns and underruns Occurs when you reference a memory beyond what you allocated. Uninitialized

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

ECE 250 / CS 250 Computer Architecture. C Programming

ECE 250 / CS 250 Computer Architecture. C Programming ECE 250 / CS 250 Computer Architecture C Programming Benjamin Lee Some slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Outline Previously: Computer is a machine

More information