Operating Systems CS 4410
Popular in Course
Popular in ComputerScienence
This 30 page Class Notes was uploaded by Lacey Collier on Saturday September 26, 2015. The Class Notes belongs to CS 4410 at Cornell University taught by Staff in Fall. Since its upload, it has received 28 views. For similar materials see /class/214335/cs-4410-cornell-university in ComputerScienence at Cornell University.
Reviews for Operating Systems
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/26/15
C for Java Programmers CS 414CS 415 Niranjan Nagarajan Department of Computer Science Cornell University niranjancscornelledu Original Slides Alin Dobra Why use C instead of Java Intermediatelevel language Lowlevel features like bit operations Highlevel features like complex datastructures Access to all the details of the implementation Explicit memory management Explicit error detection Better performance than Java All this make C a far better choice for system programming Goals of Tutorial Introduce basic C concepts need to do more reading on your own Warn you about common mistakes more control in the language means more room for mis takes C programming requires strict discipline Provide additional information to get you started compilation and execution printf debugging Hello World Example Hello World program include ltstdiohgt void mainvoid printfquotHello Worldnquot hello Hello World Primitive Types Integer types char used to represent characters or one byte data not 16 bit like in Java intshort and long versions of integer architecture dependenD can be signed or unsigned Floating point types float and double like in Java No boolean type int or char used instead Ogt false 7 Ogttrue Primitive Types Examples char c A char clOO int i 2343234 unsigned int uilOOOOOOOO float pi314 double longpi03l415el Arrays and Strings Arrays declare and allocate space for array A int AlO for int i0 iltlO i Ai0 Strings arrays of char terminated by 0 char namequotCS415quot name4 5 Functions to operate on strings in stringh strcpy strcmp strcat strstr strchr printf function oSymaXZprintfformatingstring paraml J Formating string text to be displayed containing special mark ers where values of parameters will be filled d for int C for char f for float lff0rdouble s for string Example printfquotThe number of students in s is dnquot quotC8415quot 80 enum enumerated datatypes enum months JANUARY FEBRUARY MARCH Each element of enum gets an integer value and can be used as an integer enum months JANUARY1 FEBRUARY3 MARCH Pointers address of variable index of memory location where vari able is stored first location pointer variable containing address of another variable type means pointer to variable of type type Example int i int ptrint ptrint points to some random location ptrint ampi ptrint points to integer i ptrint 3 variable pointed by ptrint takes value 3 amp address operator dereference operator Similar to references in Java Pointers c0nt l Attention dereferencing an uninitialized pointer can have arbitrary effects including program crash Good programming advice if a pointer is not initialized at declaration initialize it with NULL the special value for uninitialized pointer before dereferencing a pointer check if value is NULL int p NULL if p NULL printfquotCannot dereference pointer pnquot exit 1 Structures The record type of C like Java classes with only members struct birthday char name enum months month int day int year struct birthday mybirthday quotxyzquot111990 char FirsLetter mybirthdayname0 mybirthdaymonth FEBRUARY Structures c0nt Structures can have as elements types already defined Structures can refer to pointer to themselves struct listelem int data struct listelem next gt is syntax sugaring for dereference and take element struct listelem le 10 NULL struct listelem ptrle amp1e printfquotThe data is dnquot ptrle gtdata Datatype Synonyms o Syntax typedef type alias Example typedef int B001 B001 boolvar typedef int Intptr Intptr p p is a pointer to int typedef struct listel listel listel is alias for struct listel struct listel int data listel next this is legal Advantage easier to remember cleaner code void and Type Conversion Type conversion syntax newtype expressionoldtype Examples float fl2 int i intlf i assigned value 1 char ci implicit conversion from int to char float gi implicit conversion gl0 Extremely useful conversion is to and from void pointer to unspecified type include ltstringhgt char strllOO char str2lOO void strl memcpy void str2 100 Always do explicit conversions Common Syntax with Java Operators Arithmetic Relational ltgtltgt1 Logicalampamp 1 Bit2ampAltltgtgt Common Syntax with Java c0nt Language constructs if else while do while fori0 ilt100 i switch case 0 break continue return No exception handling statements Memory Allocation and Deallocation Global variables Characteristic declared outside any function Space allocated statically before program execution Initialization done before program execution if necessary also Cannot deallocate space until program finishes Name has to be unique for the whole program C has flat name space Memory Allocation and Deallocationcont Local variables Characteristic are declared in the body of a function Space allocated when entering the function function call Initialization before function starts executing Space automatically deallocated when function returns Attention referring to a local variable by means of a pointer for example after the function returned can have unexpected results Names have to be unique within the function only Memory Allocation and Deallocationcont Heap variables Characteristic memory has to be explicitly allocated void malloc int similar to new in Java deallocated void free void Memory has to be explicitly deallocated otherwise all the memory in the system can be consumed no garbage col lector Memory has to be deallocated exactly once strange behav ior can result othenNise Memory Allocation and Deallocati0nex l include ltstdiohgt include ltstdlibhgt int noallocvar global variable counting number of allocations void mainvoid int ptr local variable of type int allocate space to hold an int ptr int mallocsizeofint noallocvar check if successfull if ptr NULL exitl not enough memory in the system exiting ptr 4 use the memory allocated to store value 4 freeptr dealocate memory noallocvar Functions Provide modularization easier to code and debug Code reuse Additional power to the language recursive functions Arguments can be passed by value a copy of the value of the parameter handed to the function by reference a pointer to the parameter variable is handed to the function Returned values from functions by value or by reference Functions Basic Example include ltstdiohgt int sumint a int b function declaration or prototype int psumint pa int pb void mainvoid int totalsum225 call function sum with parameters 4 and 5 printfquotThe total is dquottotal definition of function sum has to match declaration signature int sumint a int b arguments passed by value return ab return by value int psumint pa int pb arguments passed by reference return ab Why pass by reference include ltstdiohgt void swapint int void mainvoid int numl5 num210 swapnuml num2 printfquotnumld and num2dnquot numl num2 void swapint n1 int n2 pass by value int temp temp n1 n1 n2 n2 temp swaptest numl5 and num210 NOTHING HAPPENED Why pass by referencec0nt include ltstdiohgt void swapint int void mainvoid int numl5 num210 int ptr ampnuml swapptr ampnum2 printfquotnuml9d and num29dnquot numl num2 void swapint pl int p2 pass by reference int temp temp pl p1 p2 p2 temp swaptest2 numl10 and num25 CORRECT NOW Pointer to Function Goal have variables of type function Example include ltstdio hgt void myprocint d do something void mycallervoid fint int param fparam call function f with param void mainvoid myproc10 call myproc mycallermyproc 10 call myproc using mycaller The Preprocessor Module support include standard library declaration include ltstdiohgt include custom declarations include quotmyheaderhquot Symbol definition behaves like final in Java define DEBUG 0 define MAXLISTLENGTH l 0 0 if DEBUG printfquotMaX length of list is dnquot MAXLISTLENGTH Conditional compilation i fdef DEBUG printfquotDEBUG line quot LINE quot has been reachednquot endif Programs with Multiple Files 0 File mypgm h void myprocvoid function declaration int mydata global variable Usually no code goes into header files only declarations 0 File mypgm C2 include ltstdiohgt include quotmyprochquot void myprocvoid mydata2 some code Programs with Multiple Files c0nt 0 File main C2 include ltstdiohgt include quotmypgmhquot void mainvoid myproc Have to compile files mpgmc and mainc to produce ob ject files mpgmcbj and mainobj mpgmc and maino on UNIX Have to linkfiles mpgmcbj maincbj and system libraries to produce executable Compilation usually automated using nmake on V ndows and make on UNIX Things to remember Initialize variables before using especially pointers Make sure the life of the pointer is smaller or equal to the life of the object it points to do not return local variables of functions by reference do not dereference pointers before initialization or after deallocation C has no exceptions so have to do explicit error handling Need to do more reading on your own and try some small programs
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'