New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Jonas Bartell


Jonas Bartell
GPA 3.77


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 38 page Class Notes was uploaded by Jonas Bartell on Monday October 26, 2015. The Class Notes belongs to CS0449 at University of Pittsburgh taught by Staff in Fall. Since its upload, it has received 21 views. For similar materials see /class/229400/cs0449-university-of-pittsburgh in ComputerScienence at University of Pittsburgh.

Similar to CS0449 at Pitt

Popular in ComputerScienence




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: 10/26/15
Common UNIX Commands General Syntax ltcommand namegt ltoptionsgt ltargumentlgt ltarg2gt ltarg3gt Cmd Syntax Examples Description Print the current wd pwd pwd p working d1rect0ry 15 List contents of a Is is ltdirectorygt is ea is la d1rect0ry cd cd cd privatefiles Change cu th working d1rect0ry man man ltcommand livid Get manual page for namegt man man command cp ltsrc pathgt cp ltdestination cp fileltxt publiccs449 CopyaFile pathgt mv ltsrc pathgt mv file2txt textfiletxt mV ltdestination mv filel txt Move or Renalne 839 pathgt publichtmlhellohtml le rm ublichtmlhello html rm rm ltpathgt rm Semp txt Delete a le mkdir ltpath to mkdir 05449 mkdlr cream mkdlr Create a d1rect0ry afspitt eduhomexxpittusrcs449 rmdir rmdlr rmdlr ltpathgt afspitteduhomeXXpittusrcs449 Remove adlrecmry h echo ltsrc echo quotA line of textquot PrintteXt t0 the ec 0 pathgt echo Another line of text terminal h Display other users W O who who whoami currently logged 1nto the system finger ltsearch finger ltyour pitt usergt Search user f39 7 7 Inger criteriagt finger Smith information cat ltpathlgt cat fileltxt file2txt file3txt cat ltpath2gt ca Concatenate les cat file3 txt gtgt file4 txt less fuel txt Display a le or any less less ltpathgt cat filel txt less output one screen at a time with scrolling more fileZ txt Display a le or any more more ltpathgt cat file2 txt more QUtput one screen at 839 t1me nd find ltpathgt find public name quot txtquot Search for les ltoption1gt ltarg1gt ltopt2gt ltarg2gt grep ltsearch Search contents of criteriagt quot n N grep ltpath or grep lthtmlgt publichtml f es filesgt chmod ux filetxt chmod 777 filetxt chmod ltnew chmod aW publicfiletxt Changef e chmod Eermiismnv Default is a all permlsSlonsUn1X pa Numeric values octal rwx 111 in OHBO binary but 7 in octal chmod 777 cmdfile listacl la list access control list listquota lg list volume quota quota show volume quota usage fs setacl set access control list ltsubcommandgt fs setacl directory user rights AFSIH y le ltargsgt rigths can be rlidwka pern sgonson AFs fs lg fs la fs setacl brown rl fs help lpr lpr ltpathgt lpr file txt Send a le to a printer zip ltdestination zip fileszip file1txt file2txt ZIP pathgt ltfi1e1gt file3 txt Create a ZIP aremve ltfile2gt Extract les from a unzq unZip ltpathgt unZip filesZip ZIP arch1ve tar ltoptiongt To put a group of les tar ltdestination tar Cf g tar A B C into one sin 1e tar xf gtar g filegt ltfile1gtm package la telnet connect to a remote u net ltaddressgt telnet unixscispittedu Sy enl ssh ssh ltaddressgt ssh unixscispittedu I connectuarmnoK ssh ltpittusrgtunixscispittedu Sy enl ecur y ftp ltaddressgt ftp unixscispittedu f etrangkrln P y em em em Dlsplay shell environment variables 1rlidwka read lookup insert delete write lock administer CS 449 File I O and Structs David Kyle dkvlchspittedu f read amp fwri te sizet freadvoid ptz sizet size sizet mnemb FILE stzeam 7 sizet fwziteconst void ptz sizet size 5139 m memb rm stzea o sizet is an integer type 0 stream in both is a FILEquot returned by fopen 0 both handle nmemb items of size bytes each 0 tojust read some number ofcharacters use size 1 set nmemb to the number desired 0 Both return number ofitems readwritten Error Handling in C 0 Standard library functions such as fread fread etc handle errors by returning some value and setting errno o The value they return varies from function to functionl often 1 o errno is a global variable defined by the standard C library 0 You can call perror print a error message fopen amp fclose rm fopenconst char path const char mode int fcloseFILE fp 0 mode can be among others quotrquot reading from the start quotwquot writing from start erases existing data first quotaquot appending writingto the end of existing data 0 FILE is an opaque type we manipulate through provided functions not directly 0 fopen returns NULL on error for fclose EOF feof amp ferror int feofE ILE stzeam int fezorFILE stzeam o fread could end due to endof file or an error 0 These functions tell us which 0 feof returns true if the file stream has reached its end 0 ferror returns true ifan error occurred during the last file function called 0 But what error f seek int fseekE ILE stzeam ong offset int whence long fte11E ILE stzeam 0 Each FILE contains a file position indicator 0 The next place to be read from or written to 0 We can reposition the indicator with fseek o offset is added to a value by whence SEEKSET zero position at the beginning SEEKCUR the current indicator position SEEKEND endoffile of39fset better be negative 0 ftell gives the indicator relative to file start fgets lchar fgetschaz 5 int size nu stzeam l o fread is fine for getting fixed width info 0 We typically work with text linebyline 0 We can use fgets to read from a file instead of an interactive user 0 Just use the FILE pointer returned by fopen instead of stdin o stdin is a virtual file that represents user input 0 stdout similarly represents console output Structs 0 They are C39s primitive version ofJava39s classes 0 Contain only data variables not functions atruct pair int a void 000 atruct pair p 12 pintfquot inquot pa prints 1 V 0 Remember structure defs end in a semicolon Packed Structs atruct peraonin o char gender M ma1e 5 female V int mstatus 1 aing1e 2 married 3 divorced V int iaretired o no 1 yes V int age atruct peraonin opacked char gender1 M ma1e 5 female V int mstatus2 1 aing1e 2 married 3 divorcedV int iaretired1 o no 1 yes V ge1239 fprintf amp snprintf int fprintfFILE stzeam const char fozmat int snprintfchaz stz sizet size const char fozmat o fprintf and snprintf are variants of printf o fprintf prints to a file instead of the console o snprintf prints to a character buffer the character buf fer starts at str at most size characters are written including 39039 0 There is also a sprintf don39t use it Structs amp Files 0 We can directly readwrite struts tofrom files atruct pair int a int mainint argc char azng 1 f39 e fope argv2 quot2quot atruct pair p3 readp sizeofp 1 file 395 S m 1 b file openargv2 quotwquot fwzite p sizeofPy 1 file c1oselt i1e CS 449 Scope Functions and Pointers David Kyle dkylchspittedu Lifetime 0 Lifetime time from allocation to deallocation of memory 0 Scope is determined at compile time 0 Lifetime is runtime but two categories Static location and size of memory allocation determined at compile time Dynamic not static Scope and Lifetime in C o In C scope is defined by Files be default all variables are limited to the file they are declared in Blocks l l a variable defined within a block has scope limited to that block 0 Variables of the same name may not coexist within the same scope Scope 0 Scope the region of code in which a symbol is legal and meaningful 0 Symbol a name which represents a constant literal or variable 0 Scope serves two purposes restrict symbols to logical divisions allow usage of same symbol for different purposes Local Variables o Are local variables static or dynamic 0 They are dynamic we don39t know how many instances will be needed 0 What about globals 0 They are static Shadowing o A variable may share the same name as another in an enclosed scope o This is called shadowing int main 39 t shadowed 4 int shadowed 6 printfquot oinquotshadowed prints 5 printfquotinquotshadowed prints 4 Global Variables 0 Global variables have scope throughout the entire program and lifetime throughout the execution of the entire program o In C variables declared outside functions have filescope they have scope within all functions in the file 0 These variables are often called global Static Global Variables o A filescope variable may be imported into other files via the extern keyword lint x 9 defined in one file l extern int x imported in another int main printf quotinquot x prints 9 return 0 o Ifa filescope variable has static in front of it extern may not be used on it Functions 0 Functions in C are much like functions in Java 0 Main difference aren39t part ofclasses 0 Also can separate declaration from definition 0 A function can be declared with its prototype lint addint 1 int r l used in the program the defined later int addint 1 int 2 return lrr39 Automatic Variables 0 Automatic variables are created and destroyed automatically usually at the start and end of a block respectively o In practice all of the variables in a function are generally created at the start of the o By default all variables declared in functions are automatic have the auto keyword Static Local Variables o A variable declared static within a function retains its value between executions o It is essentially a global variable with scope only in that function int ine static int x 0 return x39 Functions With no Arguments 0 Unlike in Java where you would define as lint printheader l you should use l int printheader void l o The former actually defines a function which can take any parameters o It can allow logic errors which would otherwise be syntax errors PassbyValue All C functions are passbyvalue This means arguments are copied from their original location into a new location void swapint a int b intta ab b int mainvoid 39 2 swapab 1n a b printfquot oinquot a quotPointersquot in Java lInteger x new Integer The value stored in x quotpointsquot to the actual Integer object Pas sby reference Pointers enable pass by reference Integer oblemHeader manna void swapint a int b 39tta ab b int mainvoid int a 1 2 swapampaampb b printfquot oinquot a retur 0 quotPointersquot in Java Perhaps the biggest feature which C has and Java doesn39t is pointers In fact Java does use pointers they39re hidden int x 7 Pointers in C In C pointers a explicitly declared 1m mainvoid int a 1 31m amp a printfquot oinquot a um printfquot oinquot ajtr aptr printfquot oinquot a printfquot oinquot ajtr const Pointers const can be used to make variables constants icons int x 8 means we cannot later do 3 9 l On the other hand lconst 1m xptr ampx xptr 9 illegal xptr ampy legal int y Pointers and Arrays We can treat pointers as arrays int arrayjtr amparray0 arrayptr 2 4r printfquotinquotarray2 prints 4 int array2ndptr array ptr 2 printf quot oinquot array2ndptr arrayjtr 2 printf quot 1inquot array 5 2 prints 5 Command Line Arguments int mainint argc char argv 5 example arg1 arg2 printfquotProgram Name snquot argv0 printfquotFirst argument snquot argv1 CSO449 Lecture 10 Processes 1 A process is a running instance ofa program a A program is the binary file created from source code stored on disk The source code is compiled and linked to create the executable file b When the program stored on disk is loaded and into memory for execution it is called a process In Linux a process is also referred to as a task i A process is more than just the program It refers to the program in memory with other attributes stored in the process control block using a task structure in Linux 1 Process ID PID gt 0 PID 0 is reserved for the swapper a Older UNIX platforms had a 16bit PID so for compatibility Linux also uses a 16bit Process ID 2 Register values for the process esp the Program counter PC base address register 3 Address space 4 Priority 5 Process accounting information such as when last run cpu time used etc 6 IO information a Opened files b IO devices etc 7 Pointers to the next and previous PCBs 2 Logical view of a program in memory The range of legal addresses for the process is known as its address space 0x7fffffff Stack 4 Heap Uninitialized Global data Initialized Global data Text segment the code 3 A process always quotbelievesquot that is has access to all the memory on a computer starting from 5 quot address 0 This is due to a technique employed by modern operating systems called Virtual Memory a However there are usually multiple processes on a system all equally deluded How do we ensure that there is little or no conflict b There should be a way to map virtual addresses to physical addresses i This is the work done by the Memory Management Unit MMU ii Even though the process thinks it starts at address 0 in reality it starts somewhere else The actual starting address is stored in the base register and the maximum address it can access is stored in the limit register When the CPU issues a memory address say address x virtual address it is added to the base register and the result compared to the limit register to make sure that the requested address is within the legal range c The Stack i Where is memory for local variables allocated ii The stack iii The stack is used for function calls iv All variables automatic allocated on the stack are deallocated popped out after the function ends v Notice that the stack grows from higher address to lower addresses d The Heap i This is where memory is allocated when the program requests for dynamic memory The allocated memory last across function calls malloc and its relatives ii The heap grows from lower addresses to higher addresses Pages a Programs may not be loaded into memory in their entirety They are done in chunks i Why 1 Consider a computer with 512MB memory Further assume that the user loads two programs iTunes and iPhoto iPhoto alone is 1579 MB on disk and iTunes 1216MB a total of 2785MB These two applications have already taken up half the amount of memory And we haven t even accounted for the hundreds of other processes running 2 Notice that there are some portions of the programs that are not always being used Why load them The OS allocates chunks of memory usually in 4k 409GB chunks called pages a Use what you need now and when you need something else that is not already in memory it will be brought in from disk Pages that contain code are marked as read only Pages that contain dynamic libraries can be marked read only and can be shared among several processes a After all the dynamic library code is not embedded in the program you re running N Process Life Cycle a Ready b Running c Blocked d Terminated When a new process is created it has to be run The OS maintains a list Linked list of processes that need to run called the ready queue The new process has to bide its time until the scheduler selects it to run for a while A running process may be blocked while it waits for IO or some other reason a The OS puts this process in the wait queue for the device When the process finishes with the IO it is put back into the ready queue and rescheduled to run When a process completes its task it terminates and the resources are reclaimed How long does each process run for Do all processes have to wait for a running process to complete before they also run What ifthe process gets into an infinite loop yikes How does the scheduler determine who goes next a There are several schemes to determine this You will learn these in detail in CS 1550 b A running process is not given free reign It has to be preempted at some point to give others a chance Each process is given a time sliceThe priority of a process is factored into who goes next i A higher priority process low number takes precedence over a lower priority one higher number 1 Most processes have a default priority of 0 2 You can use the unixLinux utility nice to change the priority ofa process a Unless you are the super user of a system you cannot boost a process to a higher priority lt 0 You can only give your process a lower priority that s why the utility is called nice Q i For instance if you have a program that is to compute PI to the hundred millionth decimal place surely you don t want it to interfere with more urgent processes If you are running a multimedia video streaming program you may want it to have a higher priority than others Why Process State Transition Diagram M or mi mmplelmn lDor wan am Blamed RelQueue If mama Queue you can use the unix top utility to monitor processes same as task manager in windows 12 Context switch This is what happens when the scheduler which is also a process The system CPU has to know where the process reached in its execution before it was rudely preempted It has to rememberthe values ofthe variables the values inside O39m the registers etc A context switch can be very expensive Imagine that the CPU has to store all these values into memow and also reload them when the process is ready to be run again 1 Moreover the cache that had been diligently filled has to be emptied and refilled when the process comes back The amount oftime that a process runs before being preempted should be orders of magnitude largerthan the context switch time 1 2 Process Creation header file ltunistdhgt The first process to be created on a UnixLinux system is called init a Init is run after the system boots up It sets up some pertinent information and then starts the system processes the scheduler PID 0 The fork system call a The fundamental process creation primitive is the fork system call i pidt forkvoid ii A successful call to fork creates an exact duplicate of the running process 1 The newly created process is referred to as the child process 2 The process the created the new one is called the parent After the child process has been created the two processes run concurrently independently iv They are both put in the ready queue waiting for a piece of the CPU 1 Do not assume which of the two will run first That is the job of the scheduler Fork returns a value after the call lt 1 Note that after the call to fork both processes resume running from the same position ie the value of the PCs of both processes are the same 2 However the return value of fork is different for the two a In the parent for returns the PID of the child b In the child fork returns 0 i This provides a convenient way to distinguish the parent from the child ii To get the childs PID use the system call getpid 3 The return value is 1 when fork fails to create a child a This can indicate that the calling process has tried to breach one of two limits i The system wide limit on the number of processes i The limit on the number of processes that any user may run simultaneously The parent and the child are identical but different They both have the same variables and gthe same values in the variables but the variables are separate from each other The parent and child can modify their copies of the variables without affecting each other 3 However file pointers are shared this is because they are maintained by the kernel and not the user process 57 So if you advance the file pointer of an open file in the child the file pointer will advance in the parent also c What disadvantage can you see about fork more on this when we talk about threads 50 why would you want to do something seemingly mundane as splitting a process into two and wasting resources a Fork is usually used in conjunction with another function exec Equot 9 b exec is a family of functions that that allow the user to execute another program different from the one currently being run 39 All members of the exec family finally make a call to the system call execve which does the actual work Aside a system call is a mechanism used by an application program to request services from the OS The system calls put the CPU into kernel mode supervisor so that they can perform critical tasks access certain memory regions perform other tasks that would be dangerous if left in the hands of the users The exec functions simply take in a name of a program to run and the arguments to the program 3 int execlconst char path const argO const argl const argn char0 b Int execpconst char file const char argO const char arg1const char argn char 0 c int execvconst char path char const argv d int execvpconst char le char const argv Exec does not create a new process It completely obliterate the current running process that called exec a That is it overwrites the process in memory b Exec never returns to whom is it returning The process that called it is no more i If it does return then it has a message of doom There was an error quotexecingquot the program include ltunistdhgt nt main printf executing lsnquot execl binlsquot llls lquot charO the current program should end here if it continues to the next line then it means that exec returned perror exec failed to run lsquot exitl The wait system call ltsystypeshgt ltsyswaithgt 7 When the parent process wishes to briefly suspend execution while the child process is running the wait system call is used a Once the child is done the parent resumes execution b If more than one child is running then wait returns as soon as one of the children exits c Wait is often called by the parent right after quotforkquot is called include ltsystypeshgt include ltsyswaithgt nt main int status iffork 0 chid do something else parent waitampstatus printf the child is deadnquot d If wait is passed a nonNULL pointer to an int the integer will contain important status information when wait returns i Other versions of the wait system call can provide other services 1 waitpid wait for a specific child with a particular pid to exit 2 wait3 wait for any child 3 wait4 wait for a specific child or children 8 The exitint status function can be used to terminate a process ltstdlibhgt 9 The atexitvoid funcvoid routine registers a function pointed by func to be called a This function is called as a cleanup routine after a call to exit b The exit status of a program can be obtained by using the S variable within the shell 10 If exit and wait are used in an orderly fashion each process is waited for a However there are two other situations i A child exits when the parent is not waiting 1 The child is placed in limbo and becomes a zombie a a zombie process is one that occupies a slot in a table maintained by the kernel for process control but uses no other kernel resources b It will be finally put to rest if its parent claims it by calling quotwaitquot ii A parent exits while one or more children are still running 1 When the children exit they are adopted by quotinitquot the parent of all processes The stack function calls and call conventions 13 A compiler cannot tell how many times a function will be called a It can therefore not statically allocate enough memory for it b The stack is used to allocate memory for the function with its parameters and local variables and deallocated when the function returns c A register called the stack pointer is used to mark the top of the stack d The stack stores the parameters and other local variables of a function i It also stores the return address of the calling function why e During a function call there should be some quotagreementquot between the calling function and the callee as to what information will be on the stack and how that information is structured f The following information are saved on the stack 39 Local variables The return address The parameters iv Temporary storage for some special registers g The stored information for a function together is called the functions activation record or the frame h The frame pointer marks the beginning of the activation record the stack pointer marks the end 14 Variadic functions 3 Some functions in C can take a variable number of arguments i For instance quotprintfquot and llscanfquot b To access the parameters of a function of variable length the stack needs to be traversed i The C library ltstdarghgt provides macros to do this include ltstdarghgt include ltstdiohgt double averageint size variable length argument double total int j 0 valist ap int main Linked Lists CS 449 Dynamic Memory J ISK J David Kyle dkylchsgittedu 0 Each element of the lIst I39pomts to the next 2 malloc Structure Pointer Operator include ltstdlib hgt 0 We use dot operator for fields from structs void mallocsizet size o What about pointers to structs 0 We could do struct example e coco e somefie1d o malloc allocates memory somewhere and returns a pointer to it o if there39s an error out of memory it returns NULL amp sets errno 0 But C gives us a short cut the arrow operator char bu fez malloc64 5 int azzay malloc16 sizeofint smut example 9 5000 egtsomefie1d n mallocsizeofstzuct node struct node memset memcpy free include ltstzinghgt void memcpYWoid 51 const void 52 sizet n void memsetWoid 5 int c sizet n include ltstdlibhgt void free void ptz o Frees memory allocated with malloc Ifyou want to say initialize an array39s values Do not can free more than once on a pointer to zero you can do so quickly with memset 0 Calling free on a null pomter Is safe char buffe malloc32 memsetbuffez o 32 0 As such setting freed pointers to NULL is a o memcpy is like strncpy except it doesn39t end gOOd quotma 0 Free must eventually be called on any pointer ata null terminator created with malloc Unions union example int asintegez int asintp char asstr float asfloat union example e easst quottestquot easintegez o pintfquot snquot easst 0 Unions39 elements overlap in memory 0 Each element is simply another name for the same area of memory Example Packed Structures struct personinfo unsigned gend unsigned age12 nion personinfouni personinfo ed short asintegez on asstuct struct sign i 0 Sometimes we might want to treat packed structs as integers especially for initialization Practical C Issues Preprocessor Directives Multie le Development and Make les David Kyle dkylecspittedu Based on slides by Jonathan Misurda de ne Textual Symbol Replacements define PI 31415926535 define MAX 1 float f PI forieiltMAXi if if ltcondition that can be evaluated by the preprocessorgt What does preprocessor know Values of defined variables Constants 6222009 include Copies the contents of the specified file into the current file lt gt indicate to look in a known location for includes quot quot indicate to look in the current directory or specified path include stdio h include quotmyheader h de ne Macros Textual replacements with parameters Good define MAXa b a gt b a b Not so good define SWAPab int ta ab bt Example include stdio h int main if B printfquotthis is not printedn endif printfquotThis is printedn return 9 6222009 Example 2 6156 include lt5tdiohgt if define VERSION 5 int main elif if VERSION lt 5 else pr 1ntfquotth1s 15 not pr1ntedn endif printfquotThis is printedn gendif return 9 ifdef Example ifde ned include lt5tdiohgt define MACRO Checks to see if a macro has been defined but doesn t care about the value int main A defined macro might expand to nothing but is ti considered defined 1 dam MACRO s printf this is printedn endif printf This is also printedn return 0 undef Shortcuts Undefines a macro ifdefined 9 ifdef include lt5tdiohgt if defined 9 ifndef define MACRO undef MACRO int main if defined MACRO printf this is not printedn endlf printf This is printedn return 0 6222009 Uses Notes Handle Operating SystemArchitecture specific Can define variables from the commandline code with D Handle differences in compilers gcc 0 test DVERSION5 testc gcc o test DMACRO testc Build program with different features Debugging ifdef DEBUG endif Other Preprocessor Details De ned Constants quotes a string iFILEi rrently compile iLINEi Thecurrentline number iDATEi Thecurrentdata W concatenates two thIngs TIME THEEWEMM STDC Defined if cum pilEr suppunsANSl c Manyothercompilerrspecificflags pragma warn error Multi le Development Static Local Scope Want to break up a program into multiple files Easierto maintain Scope Local Lifetime Global life of program Multiple authors Quickercompilation void f static int x Modularity 6222009 File Scope Example quotGlobal Variablesquot are actually limited to the ac file int x 6 include lt5tdiohgt rut rn maybe be used to Import variables int int y from other files i return Xy int main File A File B i i X 5 int x extern int x DrintFquotdquot W i return a Willrefertnthesamememnrylncatinn Compi ing Static gcc ac bc ac hc static int x 6 include lt5tdiohgt aout static int Hint y 5 return xy int main i X 5 printFquotdquot F0 return 0 Compiling Header Files gcc ac bc 0 Usually only contain declarations Variable types tmpcccyUClJAotext0x6 In Functions unction a n39 de fined macros unde Fined r e Fer ence to x39 o P d th I t t H tmpcccyUCUAo text0x19 In alre WI an Imp emen a Ion le unction quot unde Fined r e Fer ence to F39 colleth ld returned 1 exit status Including a Header File Once ifndef MYHEADERH defi ne MYH EADERH Definitions of header to only be included once endif Driver 0 Driver program include quotmymallochquot Can now use those functions Compile gcc o malloctest mymallocc mallocdriverc Make le malloctest mymalloco mallocdr iver o gcc ro malloctest mymalloco mallocdr ivero mymalloco mymallocc mymalloch gcc 7c mymallocc mallocdrivero mymalloch mallocdriverc gcc 7c mallocdr iver c 6222009 Headers and Implementation mymalloch m alloc c ma quotmyinextfitimalluzdnt size stati Mallodnfp head Wm W eewid xvquot ma quotmy nextfitimalluzdnt size nt stati Mallutlnfu quotzurre ma myifreeOuid pu l Make les Express what files depend upon others Ifany are modified build smallest set required Dependency Graph ma llnrlexl immiim i viiillDi 1mg nwnullm h mvmqiim What will this code print What will this code print printfwai39v 39a39 printfquot ocquot 39a39 a the character a a the character a b 97 ASCII code of a b 97 ASCII code of a c some arbitrary number c some arbitrary number d it may crashwill be unpredictable d it may crashwill be unpredictable e it won39t compile e it won39t compile 1 What will this code print What will this code print printf quot 1xquot printf a the character a a the character a b 97 ASCII code of a b 97 ASCII code of a c some arbitrary number c some arbitrary number d it may crashwill be unpredictable d it may crashwill be unpredictable e it won39t compile e it won39t compile a What will this code print What will this code do printf quot901 quotaquot int main void char 5 fgets s 51 stdin printfquot asquot s a the character a a accept input print the first 60 characters b 97 ASCII code of a b accept input print arbitrary text c some arbitrary number c will not accept input print arbitrary text d it may crashwill be unpredictable d it may crashwill be unpredictable e it won39t compile e it won39t compile What will this code do int mainvoid char 551 fgetss sizeofs stdin printfquot asquot s a accept input print the first 60 characters accept input print arbitrary text 039 c will not accept input print arbitrary text d it may crashwill be unpredictable e it won39t compile What will this code do assume malloc doesn39t fail int mainvoid char 5 malloc6139 fgetss s1 stdin printfquot asquot s a accept input print the first 60 characters accept input print arbitrary text n u it may crashwill be unpredictable d it won39t compile e none of the above void exampleint arr 39 How can we find the f of elements in arr a Si zeof arrs i zeof arr 0 b s i zeofarr c str39len arr d s i zeof arrs i zeof 39i nt e None of the above What will this code do assume malloc doesn39t fail int mainvoid char 5 malloc6139 fgetss sizeofs stdin printfquot asquot s a accept input print user39s input up to the first 60 characters b accept input print arbitrary text it may crashwill be unpredictable d it won39t compile n e none of the above void examplechar s How can we find the length of string 5 a Si zeofss i zeofs 0 b s i zeofs cstr1ens d s i zeofss i zeof char e None of the above int arrSOMENUMERICCONSTANT 39 How can we find the f of elements in arr a Si zeof arrs i zeofarr 0 b s i zeofarr c str39len arr d s i zeof arrs i zeof39i nt e None of the above Suppose my program tries to create a sequence of 100 random numbers using rand without first calling srand What will happen a All 100 numbers will be the same b Each run of the program will produce the same sequence c Each run of the program will produce an independant sequence of random numbers d In may crashwill be unpredictable e None of the above Assuming that a is an array of i nts which of the following is equivalent to a5 a a 5 sizeofint a 5 sizeofint a 5 a 5 None of the above 10039 e Which function carries the risk of memory leak if not handled properly What span of random numbers will this give assuming a suitable call to srand lrandn 1 5 3 l a 3 7 b 4 6 c 3 5 d 4 8 e None ofthe above Which of the following skip to the next iteration of a loop but not necessarily exit it 2 m E u 0 do e None of the above fyou39d like to write to a file blanking it first if it exists which of the following should you use a fopen exampletxt 39w39 b fopenquotexampletxt 39r39 c fopen exampletxt r None of the above d fopenquotexampletxt a e fyou39d like to write to a file appending to the end if it already exists which of the following should you use a fopenquotexampletxtquot quotwquot b fopenquotexampletxtquot39w39 c fopenquotexampletxtquotquotrquot L e fopenquotexampletxtquotquotaquot None of the above Why do we have a free function a Ithinkl know b I know what that is but I39m not sure why we need it c What39s a free function Which of the following is a valid implementation fa linked list node struct node i t value 2 struct node next b struet node int value struct node next c eitheris fine d both are erroneous Which of the following will ensure that a subsequent Fread from FILE pointer F will read from the last 200 bytes of the file a fseek b f 200 SEEKEND f 200 SEEKSET f 200 SEEKBEGN f 200 SEEKCUR None of the above fseek c fseek d fseek e What39s the difference between i and i a Ithinkl know b I know what one does but I don39t think they39re different c What39s a Is there anything wrong with this code to resize a malloc39d character buffer char resizechar old int size char ret malloesize marcpyhret old sizeofold return ret called elsewhere arr resizearr oldsize 10 a Yes b No c don39t know OXFOOF amp OXFFOO I OXFOFO OXOOOF OXFFFF Which of the following will return 1 if the nth leastsignificant bit in i nt x is l 0 otherwise How many possible values can sx take struct foo int x3 y2 21 struct foo s a 1 0392i l Jgt00 0 Which of the following will toggle the nth least significant bit in int x What kind of variable has local scope but global lifetime a b global static local n static global 0 None of the above automatic local e What will this program print void swapint a 1m 1 39n ta abbt J int main in a 1 b 2 swapa b printfquot od dnquot a b a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do an What will this program print void swapint ampa int ampb intta abbt int main Lnt a 1 b 2 swapa b printfquot od dnquot a b al 2 b2 1 c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do 31 What will this program print void swapint a int b intt a ab bt int main int a 1 b 2 swapa b printfquot od dnquot a b a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do 33 What will this program print struct foo int v void swapstzuct 00 a struct foo b i i t av av bv bv t 1 b 2 swapa b Printfquot d dnquot av bV a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do What will this program print void swapint a 1m b intta abbt int main 1m a 1 b 2 swapa b printfquot od dnquot a b a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do 32 What will this program print void swapint a int b intt a ab bt int main int a 1 b 2 swapampa ampb printfquot od dnquot a b a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do so What will this program print struct foo int v void swapstzuct 00 a struct foo b 39 tavav t 1 b 2 swapampa 5b Printfquotd dnquot av bv al 2 b2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do What will this program print struct foo int v void swapstzuct 00 a struct foo b int t agtv agtv bgtv bgtv t int mainO struct 00 a 1 b 2 swapampa sh Pzi tfquot d mmquot av bv a l 2 b 2 l c In may crashwill be unpredictable d It will not compilewill give warnings and not do what it39s supposed to do X86 In 32 Bit General Purpose Registers EAX Accumulator EBX Base ECX Counter EDX Data 6102009 CISC vs RISC x86 is the epitome ofa Complex Instruction Set Computer struction Set Architecture Hundreds of instructions Instructions have differing lengths David Kyle dkle c Based on slides by Jonathan Misurda F2XM1 Cnmpute 21 7 Can puies ine Exponential value of 2 a ine Dwer of ine source operand minus 1 rne source operand is iaaaied in register sTn and ine result is aisa stored in sTn rne value of ine source operand must iie inin 1 u If e range 71 n a mine source value is Dutsidethis range ine result is undefined Other 32 Bit Registers EIP Instruction Pointer ESP Stack Pointer EBP Base or Frame Pointer 39 EFLAGS Flag register ESI String Source EDI String Destination Register Sub elds Hello World me aim seztion rodata5tr11 ans progbit51 LZ String hello worldl tm glob main ype main funztion push p moi1 xesp Kebp sub 32 xesp and 3916e p IUJ ill MAJ 2m Sub m xesp moi1 Luz mesa all Puts moi1 w xeax leave sezt 139 ata mlrstazk pr0gbit5 iderit m GNU 346 mama Red Hat 34673 6102009 ATampT Syntax gcc and gas use ATampT syntax Opcode appended by type bibyte Sybil wiword 16rbit lilong327bit qiquad 64rbil First operand is source Second operand is destination Memory dereferences are denoted by CS 449 Introduction to C David Kyle dkylchspittedu Comments 0 Like in Java you can insert comments 0 You should only use the version is not always available it is in C 0 For example 1nt 1 1 set variable 1 to one l 0 See chapter 3 in the book for programming style suggestions you will be expected to use reasonable style for your projects and labs Statements 0 Just like Java C executes code as sequences of statements 0 Each statement ends in a semicolon o For example l printf Hello Worldn l is a statement composed ofa function call with a string argument Hello World include ltstdiohgt int mainvoid l printfquotHello worldlnquot return 0 Basic Program Structure 0 Our program begins with header includes such as include ltstdio hgt You may need to include other headers such as stdlib h in the future 0 Every program needs a main function which begins with 1nt malnvold l and ends with return 0 Expressions 0 As in Java expressions are building blocks of computation o The basic operators and their order ofoperations are the same as Java 0 For example 123 is an expression while 12 3 l is a statement Variables 0 As in Java variables store values names start with either a letter or underscore continue with any number of letters digits or underscores names are case sensitive 0 Names are traditionally lowercase unlike Java eg entryitotal rather than entryTotal Assignment 0 As in Java use a single equal sign to store the right side in the left side 0 For example l total 123 store 9 in total l 0 As in Java you can assign a value at time of l int total 123 store 9 in total l 0 And there are the same short cuts eg Integer Representation o Integer values are represented by a specific numberofbinary digits 0 For example l short total 27 l would be represented by l6bits 0000000000011011 0 Negative numbers are 2 s compliment l1111111111111111 quot21111111111111110 Variable Declarations 0 Unlike in Java all variables must be declared at the start of a block for now the beginning of the main function mt malnVOld l mt mumOld l in 1 1n 1 2Lan 3 12 12 mt 3 return 0 return 0 l ls legal Is not legal Types 0 Each variable declaration specifies a type 0 C includes the following builtin types char Aslngle character Dr byte 1 byte 8 blts 1n An lnteger 4 bytes 1mg An We m 4 bytes 1m long A We s m 1mg 8 bytes share A We m 2 bytes float Slnglespreclslonfloatlng bbmt yalue 4 bytes double Dbublebremslbn batmg bbmt yalue 8 bytes Uns1gned Types 0 Each integer type has an unsigned variant egunsigned int 0 The values in these variables are always gt 0 o This enables larger numbers to be stored Characters Escape Characters 0 A variable of char type can store either a small number or a single lettersymbol 0 Letters and symbols are referenced by their ASCII value see Appendix A for the values 0 To get the value ofa letter or symbol use 0 Certain characters are useful yet cannot be directly typed in such as a line break o In C as in Java we use a backslash followed by a letter or number to represent those single quotes for example n Newlineonlyun Unixrlikesystems n Null charmer useful for strings l char letter 39a39 store 97 l t Emma 39 Singlerquoteapustmphe quot Doublerquute Backslash prantf prantf elds I l printfquotc dnc adquot 39A39 3 39B39 4 printf Is a function defIned In the stdlIbh header file 0 Each field acts as a placeholder It can take any number of parameters 0 The character after the determines the type 0 The first parameter is always the quotformatquot 33339 expect c for Char and d for dlglt 1n o In general the format string is printed asis Each value comes from remaining arguments like in the hello world program order in which the a ear in the format 0 The format can contain fields which start with I pp the symbol 0 Result from above 3 Comparison Operators Boolean Operators 0 We have the same comparison operators as Java eg i l lt gt lt gt 0 We have the same logical operators as Java eg ampamp 0 These work as expected with the same truefalse scheme as the comparison operators 0 Unlike in Java there is no boolean type o In C zero for any integer type is treated as false and any nonzero value as true 0 The comparison operators are guaranteed to return values consistent with that scheme but not necessarily one for true 0 These operators quotshortcircuitquot as in Java lfthe result of the leftside determines the ultimate result the rightside is not executed l 1 2 ampamp printfquotwont39t get print8dnquot BitWise Operators BitWise AND 18 amp 17 0 We can operate on the bIt level ofIntegers using bitwise operators 0 The bits of each side are ANDed together These same operators are also InJava butless 18 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 often used amp17 0000000000010001 1 BTVWTSEAND l BitwiseOR 16 0000000000010000 VA 328 iquotgtlt 8 invert bits e BitWise OR BitWise XOR 18 amp 17 o The bits of each side are XORed together 18ampl7 o The bits of each side are ORed together 180000000000010010 180000000000010010 amp170000000000010001 amp170000000000010001 190000000000010011 30000000000000011 Left shift Right shift 18 gtgtl 18 ltlt3 l o The bits of the left side are shifted to the right 0 The bits ofthe leftside are shifted to the left bythe amounton the rightside bythe amounton the rightside 180000000000010010 180000000000010010 30000000010010000 gtgt10000000000001001 gtgt20000000000000100 0 Note that zeros are added on the right 0 Note that zeros are added on the left Bit inversion 18 o All ofthe bits are inverted 180000000000010010 N181111111111101101


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


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'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.