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

Computer Systems and Programm

by: Leland Swift

Computer Systems and Programm CS 367

Marketplace > George Mason University > ComputerScienence > CS 367 > Computer Systems and Programm
Leland Swift
GPA 3.66


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 33 page Class Notes was uploaded by Leland Swift on Monday September 28, 2015. The Class Notes belongs to CS 367 at George Mason University taught by Staff in Fall. Since its upload, it has received 58 views. For similar materials see /class/215127/cs-367-george-mason-university in ComputerScienence at George Mason University.

Similar to CS 367 at Mason

Popular in ComputerScienence


Reviews for Computer Systems and Programm


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/28/15
Introduction to C Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers and dynamic memory Acknowledgement These slides are adapted from lecture slides made available by Prof Dave 039 Halloran Carnegie Mellon University What we will cover A crash course in the basics of C You should read the textbook Ch 11 19 or the Kernighan amp Richie C book for lots more details Like Java like C Operators same as Java Arithmetic i1 i i i 2 39 IR Relational and Logical l I gt ampamp II amp I Syntax same as in Java 7 if iielseii 7 While l 1 7 do i 1 while 7 foril i lt 100 i 1 7 switch case 1 m 1 7 continue break Java programmer gotchas 1 int i fori 0 i lt 10 i NOT forint i 0 i lt 10 i datatype char short int long float double Simple Data Types size values 1 128 to 127 2 32768 to 32767 4 2147483648 to 2147483647 4 2147483648 to 2147483647 4 34E38 7 digits 8 17E308 15 digits long Java programmer gotchas 2 Uninitialized variables catch with Wall compiler option include ltstdio hgt int mainint argc char argv int i factorial i return 0 Java programmer gotchas 3 Error handling No exceptions Must look at return values Breaking down the code include ltstdiohgt Include the contents of the file stdioh Case sensitive lower case only No semicolon at the end of line int main The OS calls this function when the program starts running printfformatstring argl Prints out a string specified by the format string and the arguments Good evening include ltstdiohgt int mainint argc char argv print a greeting printf quotGood eveningnquot return 0 goodevening Good evening formatstring Composed of ordinary characters not Copied unchanged into the output Conversion specifications start with Fetches one or more arguments For example char c Chatquot 35 int 25 float f For more details man 3 printf C Preprocessor define C5367 Cemputer Systems amp Programmingnquot int mainint argc char argv printfCS367 return 0 Conditional Compilation define C5367 int mainint argc char argv ifdef C5367 printfquotComputer Systems amp Programmingnquot else printfquotSome other classnquot endif return 0 After the preprocessor gcc E int mainint argc char argv printfquotComputer Systems amp Programmingnquot return 0 After the preprocessor gcc E int mainint argc char argv prnmf Cemputer Systems amp Programmingmw return 0 Command Line Arguments 1 Command Line Arguments 3 int mainint argc char argvn cmd39ine Computer Systems and Programing argc 5 arguments Number of arguments including program name 0 cmdllne 1 Computer argv 2 Systems Array of charquots that Is an array of c strings 3 and 7 argv0 program name 4 Programming 7 argv1 first argument s 7 argvargc 1 last argument Command Line Arguments 2 Arrays include ltstdiohgt char foo 80 An array of 80 characters int mainint argc char argv sizeoffoo 80 X sizeofchar int i 80 X1 80 bytes printfquotd argumentsnquot argc int bar40 f ri 0 i lt argc 1 An array of 40 integers printfquot d snquot i argvi 7 sizeof bar return 0 40 X sizeofint 40x4160bytes Structures Aggregate data include ltstdio hgt struct name chaz name int age 1 lt Do NOT FORGET the semicolon int mainint azgc chaz agv struct name bovik bovikmame quotHarry Bovikquot bovikage 5 printEC39Vss is ad years oldnquot bovikname bovikage n 0 Memory layout and addresses Lntx5 y10 float f 12 5 g 98 char c c d 4300 4304 4308 4312 f f 4317 4316 Pointers Pointers are variables that hold an address in memory That address contains another variable Using Pointers 1 float f float faddr data variable pointer variable faddr any oat 4300 43 04 any address amp address operator faddr 4300 4304 Pointers made easy 2 faddr 32 indirection operator f faddr 4300 4304 float g faddr indirection g is now 32 f 13 but g is still 32 f faddr 4300 4304 Example 1 swapl void swap1int a int b Q Let x3 y4 after swapl xy X y A2 x3 y4 Function Parameters Function arguments are passed by value What is pass by value The called function is given a copy of the arguments What does this imply The called function can t alter a variable in the caller function but its private copy Three examples Example 2 swap2 void swap2int a int b Q Let x3 y4 after swap2ampxampy x y W A2 x4 y3 Example 3 scanf Not likeJava include ltstdio hgt Q Why using I NO new Pointers in scanf No garbage collection Lnt ma1n A We need to assign You ask for H bytes int x thevauetox N Not a highlevel request such as scanf dn ampx a printf dn x Id like an Instance of class String Dynamic Memory malloc Java manages memory for you C does Alocates memory in the heap not Lives between function invocations C requires the programmer to explicitly allocate and deallocate memory Unknown amounts of memory can be allocated dynamically during runtime with malloc and deallocated using free Example Allocate an integer oint iptr int mallocsizeofint Allocate a structure ostruct name nameptr struct name mallocsizeofstruct name Pointers and Arrays Pointer Address of a variable in memory Allows us to indirectly access variables 39 gt in other words we can talk about its address C rather than its value TOpICS Array A list of values arranged sequentially in memory Example a list of telephone numbers Expression 3 4 refers to the 5th element of the array 3 Passing Arrays as Arguments C passes arrays by reference the address of the array ie of the first element is written to the function39s activation record otherwise would have to copy each element main Pointers and Arrays nmerstmmw mean Averagenumbers int Averageint inputValues MAXNUMS for index 0 index lt MAXNUMS index sum sum indexValuesindex return sum MAXN39UMS A String is an Array of Characters Allocate space for a string just like any other array char outputstring16 Space for string must contain room for terminating zero Special syntax for initializing a string char outputstring16 quotResult quot which is the same as outputstring0 R outputstring1 e outputstring2 5 Common Pitfalls with Arrays in C Overrun array limits There is no checking at runtime or compiletime to see whether reference is within array bounds int array10 for i 0 i lt 10 i arrayi 0 Declaration with variable size Size of array must be known at compile time void SomeFunctionint nume1ements int temp nume1ements Relationship between Arrays and Pointers An array name is essentially a pointer to the first element in the array char word10 char cptr cptr word points to word0 Difference Can change the contents of cptr as in cptr cptr 1 The identifier quotwordquot is not a variable Pointer Arithmetic Address calculations depend on size of elements C does size calculations under the covers depending on size of item being pointed to double x10 double y x r y 3 13 same as x3 base address plus 6 I Data Structures Structures in C A struct is a mechanism for grouping together related data items of different types Recall that an array groups items of a single type Example We want to represent an airborne aircraft char flightNum7 int altitude int longitude int latitude int heading double airSpeed We can use a struct to group these data together for each plane Data Structures A data structure is a particular organization of data in memory We want to group related items together We want to organize these data bundles in a way that is convenient to program and efficient to execute An array is one kind of data structure In this chapter we look at two more struct directly supported by C linked list built from struct and dynamic allocation Defining a Struct We first need to define a new type for the compiler and tell it what our struct looks like struct flightType char flightNum7 max 6 characters int altitude in meters int longitude in tenths of degrees int latitude in tenths of degrees int heading in tenths of degrees double airSpeed in kmhr l This tells the compiler how big our struct is and how the different data items members are laid out in memory But it does not allocate any memory Declaring and Using a Struct To allocate memory for a struct we declare a variable using our new data type struct flightType plane planefightNum0 Memory is allocated and we can access individual members of this Variable planefightNum6 plane airSpeed 800 0 PlanealtitUde planealtitude 10000gtlt planelongitude planelatitude A struct s members are laid out in the order specified by the definition planeheading planeairspeed 13 typedef C provides a way to define a data type by giving a new name to a predefined type Syntax typedef lttypegt ltnamegt Examples typedef int Color typedef struct flightType WeatherData typedef struct abtype int 3 double b ABGroup Defining and Declaring at Once You can both define and declare a struct at the same time struct flightType char flightNum7 max 6 characters int altitude in meters int longitude in tenths of degrees int latitude in tenths of degrees int heading in tenths of degrees double airSpeed in kinhr maverick And you can use the flightType name to declare other structs struct flightType iceMan Using typedef This gives us a way to make code more readable by giving applicationspecific names to types Color pixels500 Flight planel plane2 Typical practice Put typedef s into a header file and use type names in main program If the definition of ColorFlight changes you might not need to change the code in your main program file Array of Structs Can declare an array of structs Flight planes100 Each array element is a struct 7 words in this case To access member of a particular element planes34altitude 10000 Because the and operators are at the same precedence and both associate lefttoright this is the same as planes34 altitude 10000 Passing Structs as Arguments Unlike an array a struct is always passed by value into a function This means the struct members are copied to the function s activation record and changes inside the function are not reflected in the calling routine s copy Most of the time you ll want to pass a pointer to a struct int CollideFlight planeA Flight planeB if planeA gtaltitude planeB gtaltitude l else return 0 Pointer to Struct We can declare and create a pointer to a struct Flight planePtr planePtr ampplanes 34 To access a member of the struct addressed by planePtr planePtr altitude 10000 Because the operator has higher precedence than this is NOT the same as planePtraltitude 10000 C provides special syntax for accessing a struct member through a pointer planePtr gtaltitude 10000 Dynamic Allocation Suppose we want our weather program to handle a variable number of planes as many as the user wants to enter We can t allocate an array because we don t know the maximum number of planes that might be required Even if we do know the maximum number it might be wasteful to allocate that much memory because most of the time only a few planes worth of data is needed Solution Allocate storage for data dynamically as needed malloc The Standard C Library provides a function for allocating memory at runtime malloc void mallocint numBytes It returns a generic pointer void to a contiguous region of memory of the requested size in bytes The bytes are allocated from a region in memory called the heap The runtime system keeps track of chunks of memory from the heap that have been allocated Example int airbornePlanes Flight planes printf How many planes are in the airquot scanf dquot EairbornePlanes planes Flight mallocsizeofFlight airbornePlanes Using malloc To use malloc we need to know how many bytes to allocate The sizeof operator asks the compiler to calculate the size of a particular type planes mallocn sizeofFlight We also need to change the type of the return value to the proper kind of pointer this is called casting planes Flight mallocn sizeofFlight free Once the data is no longer needed it should be released back into the heap for later use This is done using the free function passing it the same address that was returned by malloc void free void If allocated data is not freed the program might run out of heap memory and be unable to continue The Linked List Data Structure A linked list is an ordered collection of nodes each of which contains some data connected using pointers Each node points to the next node in the list The rst node in the list is called the head The last node in the list is called the tail NULL Example Car Lot Create an inventory database for a used car lot Support the following actions Search the database for a particular vehicle Add a new car to the database Delete a car from the database The database must remain sorted by vehicle ID Since we don t know how many cars might be on the lot at one time we choose a linked list representation Linked List vs Array A linked list can only be accessed sequentially To find the 5th element for instance you must start from the head and follow the links through four other nodes Advantages of linked list Dynamic size Easy to add additional nodes as needed Easy to add or remove nodes from the middle of the list just add or redirect links Advantage of array Can easily and quickly access arbitrary elements Car data structure Each car has the following characterics vehicle ID make model year mileage cost Because it s a linked list we also need a pointer to the next node in the list typedef struct carType Car struct carType int vehicleID char make20 Car next ptr to next car in list Scanning the List Searching adding and deleting all require us to find a particular node in the list We scan the list until we find a node whose ID is gt the one we re looking for Car ScanListCar head int searehIn Car previous current previous head head gtnext Traverse until ID gt searehID while eurrent1NULL ampamp eurrent gtvehiele1n lt searchIDH previous eurren eurrent current gtnext return previous Excerpts from Code to Add a Node newNode Car malleesizeef ar initialize node with new ear info prevNode SeanListhead newNede gtvehiele1n nextNode prevNodegtnext if nextNode NULL i L17D1 i V171 prevNodegtnext newNode newNodegtnext nextNode else printf Car already exists in database free newNode Adding a Node Create a new node with the proper info Find the node if any with a greater vehiclelD Splice the new node into the list Deleting a Node Find the node that points to the desired node Redirect that node s pointer to the next node or NULL Free the deleted node s memory NULL NULL Excerpts from Code to Delete a Node printf Enter vehicle ID of car to deletenquot scanf dquot vehicleID preVNode ScanListhead vehicleID delNode preVNode gtnext if delNode NULL ampamp delNode gtvehic1eID vehicleID preVNode gtnext delNode gtnext free delNode l else printf Vehic1e not found in databasenquot HQ in C Building on Linked Lists The linked list is a fundamental data structure Dynamic Easy to add and delete nodes The concepts described here will be helpful when learning about more elaborate data structures Trees Hash Tables Directed Acyclic Graphs Unix Files A Unix le is a sequence of m bytes Ba 5 Bk Em All lO devices are represented as files 0 devsda2 usr disk partition devtty2 terminal Even the kernel is represented as a file devkmem kernel memoryimage proc kernel data structures Unix File Types Regular file Binary or text file Unix does not know the difference Directory file A file that contains the names and locations of other files Character special and block special files Terminals character special and disks block special FIFO named pipe A file type used for interprocess comunication Socket A file type used for network communication between processes Standard lO Functions The C standard library libc 3 contains a collection of higherlevel standard lO functions Documented in Appendix B of KampR These functions are implemented on top of UNIX lO Most programmers do not need to use UNIX lO We will revisit UNIX lIO later Examples of standard lO functions Opening and closing files fopen and fclose Reading and writing bytes fread and fwrite Reading and writing text lines fgets and fputs Formatted reading and writing fscanf and fprintf Unix NO The elegant mapping of files to devices allows kernel to export simple interface called Unix lO Key Unix idea All input and output is handled in a consistent and uniform way Basic Unix lO operations system calls Unix lO vs Standard lO Standard lO is implemented using lowlevel Unix lO fopen fdopen Opening and closing files gt open and close Changing the current le position seek gt lseek Reading and writing a file gtread and write f read fwri te 0 application program sscanf sprintf fgets fputs fflush Standard lO fseek functions f m I I write k UnlxlO functions stat Close accessed via system calls 40 Standard IIO Streams Standard IIO models open files as streams Abstraction for a file descriptor and a buffer in memory C programs begin life with three open streams defined in stdioh stdinstandard input stdout standard output stderr standard error include ltstdiohgt extern FILE stdin standard input descriptor 0 extern FILE stdout standard output descriptor 1 extern FILE stderr standard error descriptor 2 int main fprintfstdout Hello worldn I Text Streams All characterbased HQ in C is performed on text streams A stream is a sequence of ASCII characters such as o the sequence of ASCII characters printed to the monitor by a single program the sequence of ASCII characters entered by the user during a single program the sequence of ASCII characters in a single file Characters are processed in the order in which they were added to the stream Eg a program sees input characters in the same order as the user typed them Standard input stream keyboard is called stdin Standard output stream monitor is called stdout 41 43 Basic IIO Functions Character IIO The standard lO functions are declared in the lt5tdi0hgt header le putchar c Adds one ASCII character c to stdout getchar Reads one ASCII character from stdin Function Description Putehar Displays an ASCII Ghana to the screen These functions deal with quotrawquot ASCII characters getchar Reads an ASCII character from the keyboard no type conversion is performed printf Displays a formatted string scanf Reads a formatted string Char c 39h39 fopen Opencreate a file for lO h u C ar C fprintf Writes a formatted string to a file p EaCh Of these calls putcha h prints 39h39 to the screen fscanf Reads a formatted string from a file putchar 104 42 44 Buffered IIO In many systems characters are buffered in memory during an lO operation Conceptually each IIO stream has its own buffer Keyboard input stream Characters are added to the buffer only when the newline character ie the quotEnterquot key is pressed This allows user to correct input before confirming with Enter Output stream Characters are not flushed to the output device until the newline character is added Output Buffering putchar39a39 generate some delay for i0 iltDELA i sum 1 putchar b putchar n User doesn39t see any character output until after the delay a is added to the stream before the delay but the stream is not flushed displayed until n is added 45 47 Input Buffering Formatted IIO Printf and scanf allow conversion between PrintfquotInP t Character 11Wquot v ASCII representations and internal data types 1nchar1 getchar Printf quotinput Charafter 21Wquot quot Format string contains text to be readwritten Cha 96 th 0 39 and formatting characters that describe After seeing the first prompt and typing a single how data IS to be readwr39tten39 character nothing happens Expect to see the second prompt but character not Std spine seqma 39frteger t b added to stdin until Enter is pressed f 5399quot ma a mg39po39n quotum er x unsigned hexadecImal number When Enter Is pressed newllne Is added to stream b unsigned binary number and is consumed by second getchar Etc ASCII character SO inChar2 is Set to n s String 46 48 Special Character Literals Certain characters cannot be easily represented by a single keystroke because they correspond to whitespace newline tab backspace o are used as delimiters for other literals quote double quote These are represented by the following sequences n newline t tab b backspace backslash 39 single quote quot double quote Missing Data Arguments What happens when you don39t provide a data argument for every formatting character printfquotThe value of nothing is dnquot 56 will convert and print whatever is on the stack in the position where it expects the first argument In other words something will be printed but it will be a garbage value as far as our program is concerned Onnn ASCII code nnn in octal xnnn ASCII code nnn in hex 49 51 printf scanf Prints its first argument format string to stdout with all formatting characters replaced by the ASCII representation of the corresponding data argument int a 100 int b 65 char c 2 char banner10 quotHolalquot double pi 314159 printfquotThe variable a decimal dnquot a printfquotThe variable a hex xnquot a printfquotThe variable a binary bnquot a printfquot a plus b as character cnquot ab printfquotA char ct A string sn A float fnquot c banner pi Reads ASCII characters from stdin matching characters to its first argument format string converting character sequences according to any formatting characters and storing the converted values to the addresses specified by its data pointer arguments char name100 int bMonth bDay bYear double gpa scanfquots ddd lfquot name EbMonth EbDay EbYear Egpa scanf Conversion For each data conversion scanf will skip whitespace characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value 356 Reads until first nondigit x Reads until first nondigit in hex 355 Reads until first whitespace character Literals in format string must match literals in the input stream Data arguments must be pointers because scanf stores the converted value to that memory address Bad scanf Arguments Two problems with scanf data arguments 1 Not a pointer int n 0 scanfquotdquot r1 39 Will use the value of the argument as an address 2 Missing data argument scanfquotdquot Will get address from stack where it expects to find first data argument If you39re lucky program will crash because of trying to modify a restricted memory location eg location 0 Otherwise your program will just modify an arbitrary memory location which can cause very unpredictable behavior scanf Return Value The scanf function returns an integer which indicates the number of successful conversions performed This lets the program check whether the input stream was in the proper format Example scanfquots ddd 1fquot name EbMonth EbDay EbYear Egpa Input Stream Return Value Mudd 021669 302 5 Muss 02 16 69 302 2 Doesn39t match literal 39I39 so scanf quits after second conversion File NC A file is a sequence of bytes stored on some device Allows us to process large amounts of data without having to type it in each time or read it all on the screen as it scrolls by A file could contain ASCII characters if it is a text file or binary data eg executables image files object files etc Text files are read or written using fscanf and fprintf Binary files are read and written using fread and fwrite Each file is associated with a stream May be input stream or output stream or both The type of a stream is a quotfile pointerquot declared as FILE infile The FILE type is defined in ltstdiohgt fopen The fopen pronounced quoteffopenquot function associates a physical file with a stream FILE fopenchar name char mode First argument name The name of the physical file or how to locate it on the storage device This may be dependent on the underlying operating system Second argument mode How the file will be used quot rquot read from the file quotwquot write starting at the beginning of the file quotaquot write starting at the end of the file append fread and fwrite Binary files are read and written using fread and fwrite sizet freadvoid ptr sizet size sizet memb FILE stream sizet fwritevoid ptr sizet size sizet memb FILE stream The function fread reads mnemb objects each size bytes long from the stream pointed to by stream storing them at the location given by ptr The function fwrite writes mnemb objects each size bytes long to the stream pointed to by stream obtaining them from the location given by ptr Both functions advance the file position indicator for the stream by the number of bytes read or written They return the number of objects read or written If an error occurs orthe endof file is reached the return value is a short object count or zero 59 Example showing using of fread and fwrite to read and fprmtf and fscanf write blocks of binary data Once a text file is opened it can be read or written using fscanf and fprintf respectively mC39Ude Skimh int main These are just like scanf and printf 0 except an additional argument specifies a file pointer int row column FILE mystream int close error fprlntfoutf11e quot The answer 15 dnquot x Char mymlename my numbersdarn sizet objectsize sizeofint fscanf infile quot s ddd 1fquot sizet objectcount 25 name EbMonth EbDay EbYear Eg39pa sizet opreturn 58 Example cont d int myarray55 2 4 6 810 1214161820 22 24 26 2830 32 34 36 3840 42 44 46 4850 printf quotInitial values of arraynquot for row 0 row lt 4 row for column 0 column lt4 coumn printf quotd myarrayrowcoumn printf quotnquot Example cont d printf quotNow reading data back innquot mystream fopen myfiename quotrquot opreturn fread ampmyarray objectsize objectcount mystream if opreturn objectcount printf quotError reading data from filenquot else printf quotSuccessfully read data from filenquot for row 0 row lt 4 row for column 0 column lt4 coumn printf quotd myarrayrowcoumn printf quotnquot Close stream skip errorchecking for brevity of example fclose mystream return 0 Example cont d mystream fopen myfiename quotwquot opreturn fwrite ampmyarray objectsize objectcount mystream if opreturn objectcount printf quotError writing data to filenquot se printf quotSuccessfully wrote data to filenquot Close stream skip errorchecking for brevity of example fclose mystream printf quotZeroing arraynquot for row 0 row lt 4 row for column 0 column lt4 coumn myarrayrowcoumn 0 printf quotd myarrayrowcoumn printf quotnquot Debugging Debugging with High Level Languages Goals Examine and set values in memory Execute portions of program Stop execution when and where desired Want debugging tools to operate on highlevel language constructs Examine and set variables not memory locations Trace and set breakpoints on statements and function calls not instructions but also want access to lowlevel tools when needed Syntactic Errors Common errors missing semicolon or brace misspelled type in declaration One mistake can cause an avalanche of errors because compiler can39t recover and gets confused main missing semicolon int 1 int j for i 0 i lt 10 i j i 397 printfquotd x 397 dnquot i j 65 67 Types of Errors Semantic Errors Syntactic Errors Common Errors Input code is not legal Missing braces to group statements together Caught by compiler or other translation mechanism Confusing assignment with equality Wrong assumptions about operator precedence associativity Semantic Errors Wrong limits onforloop counter Legal code but not what programmer intended ummt39allzed vanables Not caught by compiler because syntax is correct h missing braces ma i so printf not part of if Lnt L Algorithmic Errors int j Problem with the logic of the program for i 0 i lt 10 i Program does what programmer intended 3 f 1 7quot but it doesn39t solve the right problem Print wd x 7 dnquot 39 139 3 quot l 66 68 Algorithmic Errors Design is wrong so program does not solve the correct problem Difficult to find Program does what we intended Problem might not show up until many runs of program Maybe difficult to fix Have to redesign may have large impact on program code Classic example Y2K bug only allow 2 digits for year assuming 19 Sou rceLevel Debugger euse7smreewanw F12 Run yew ml Help e at mom ulmc lla gsa gt EIM xh 1 a ji1u ggg 1 hinclune stainm L 2 3 int alluulut n u main window 5 39 t 39 s 2quot quotaquot of Cygwm 1e 1 value 4 verslon of gdb 7 int in 3 int sum 1 value nf 102030 n x y 1u an lt 11 printfquotlnput a uuuner n 7 12 scanfquotX quot tin 1a IIIIIIIIIIII 7 15 Sum 7 allxuu11u 7 15 printfquotfhe allxuu nF xe is xenquot in sun 17 7 1s gtuulle in gt n 1y 2n 21 int alluulut n 22 x lteratluu cnunt e x nesult tn ne returueu e a 7 25 1e rnls lnnp calculates Sum e 7 27 j ey aeyam staepee atllne 14 MIXum v min v S REE v 739 71 Debugging Techniques AdHoc Insert printf statements to track control flow and values Code explicitly checks for values out of expected range etc Advantage gt No special debugging tools needed Disadvantages gt Requires intimate knowledge of code and expected values gt Frequent recom pile and execute cycles gtlnserted code can be buggy SourceLevel Debugger Examine and set variable values Tracing breakpoints singlestepping on sourcecode statements SourceLevel Debugging Techniques Breakpoints Stop when a particular statement is reached Stop at entry or exit of a function Conditional breakpoints Stop if a variable is equal to a specific value etc Watchpoints Stop when a variable is set to a specific value SingleStepping Execute one statement at a time Step quotintoquot or step quotoverquot function calls gtStep into next statement is first inside function call gtStep over execute function without stopping gtStep out finish executing current function and stop on exit 72 Programming in C in a UNIX environment Programming Tools Several Integrated Development Environments IDES Visual Studio Netbeans Eclipse jGRASP IDEs are great but there is a learning curve But you don t need to use an IDE You need a Text Editor use vi or emacs orjEdit not PICOII Compiler use gcc in conjunction with the Make utilit Debugger use gdbllnsight Become familiar and comfortable with UNIX See useful links on class web page Links to several tutorials on UNIX gdb make emacs vi etc 3 Software Development Lifecycle Program With multiple files include ltstdiohgt inCJude lt5tdi hgt Understand the reqUIrements include mypgmmquot include mypg39mhquot Develop the algorlthmapproach veid mainWOid void mwrouvoid Write the code Debug the code myproc mydatai T tth d somecode es e co e hwc mypgmc Iterate until you get it right Library headers Standard veld myprocvod Userdefined int mydata mypgmh EXtems Example cont d include ltstdio hgt ExternVarsh extern char useerine 20 global variable defined in another file I I char userlline30 global for this file eXtern Char LlneMaXLJ ne void dummyvoid extern int NChars NWords NLines LineLength void mainvoid char userlline20 different from earlier userlline30 Defsh restricted to this func l define MaxLine 200 void dummy extern char userlline the global userlline30 Majnc Exampe to show separate compiation and make introductory c program implements a subset of the Unix wc command reports character word and line counts in this version the quotfilequot is read from the standard input ConSIder a program whlch Is splIt Into several files WIth each function in a separate file Note this is just for wl me quotDefs39hquot illustrating the use of makell extern int ReadLine WordCount char LineMaxLine one line from the file int NChars 0 number of characters seen so far Defsh Mainc ReadLineC NWords 0 number of words seen so far NLines 0 number of lines seen so far WordCountc ExternVarsh PrintLinec LineLength length of the current line UpdateCountsc main while 1 LineLength ReadLine if LineLength 0 break UpdateCounts printf quotd d dnquotNCharsNWordsNLines Computer Systems amp Programming CS 367 Section 001 Prof Pearl Wang Section 002 Prof Elizabeth White Spring 2009 Course Goals cont d Abstractions have limits Especially in the presence of bugs Need to understand underlying implementations Useful outcomes Become more effective programmers gtAble to find and eliminate bugs efficiently gtAble to tune program performance Prepare for later systems classes in CS amp ECE gtCompilers Operating Systems Networks Computer Architecture Course Goals Previous courses CS 112 CS 211 highlevel programming in JavaC This course exposes you to C and assembly programming C is a procedural language not objectoriented Commonly used for lowlevel systems programming and embedded systems Theme of the course strip away abstractions provided by highlevel languages such as Java and let you understand what goes on under the hood Great Reality 1 Int39s are not Integers Float39s are not Reals Examples ls x2 Z 0 gt Float s Yes gt Int s 40000 40000 gt 1600000000 50000 50000 gt lsxyz xyz gt Unsigned amp Signed Int s Yes gt Float s 1 e20 1e20 314 gt 314 1e20 1e20 314 gt Computer Arithmetic Does not generate random values quot quotL quot quot quot 39 properties Cannot assume usual properties Due to niteness of representations Integer operations satisfy ring properties gtCommutativity associativity distributivity Floating point operations satisfy ordering properties gtMonotonicity values of signs Observation Need to understand which abstractions apply in which contexts Important issues for compiler writers and serious application programmers Great Reality 3 Memory Matters Memory is not unbounded It must allocated and managed Many applications are memory dominated Memory referencing bugs especially pernicious Effects are distant in both time and spa Memory performance is not uniform 39 Crath Ilru 39 performance Adapting program to characteristics of memory ayatem can lead to major speed improvements a y Great Reality 2 You39ve got to know assembly Chances are you ll never write program in assembly Compilers are much better I more patient than you are l r Behavior of programs In presence of huge gt Highlevel language model break down Tunlng program performance gt ratandlng sources of program lne lclency Implementing eyetem aoftvra Compiler has machine code as target gt operating eyetems must manage process state Memory Referencing Bug Example main I 1ong int an 0 1e d 314 a2 1073741324 out of bounds reference printfquotd 9s159nquot d exit0 I Alpha MP5 Linux g 530498947741318e315 31399998664856 314 o 314 314 314 Linux version gives correct result but implementing as separate function gives segmentation fault Memory Referencing Errors C and C do not provide any memory protection Out of bounds array references Invalid pointer values Abuses of malloclfree Can lead to nasty bugs Whether or not bug has any effect depends on system and compiler Action at a distance gt Corrupted object logically unrelated to one being accessed gt Effect of bug may be first observed long after it is generated How can I deal with this Program in Java Lisp or ML Understand what possible interactions may occur Use or develop tools to detect referencing errors Course Perspective Cont This Course is ProgrammerCentric Purpose is to show how by knowing more about the underlying system one can be more effective as a programmer Enable you to gtWrite programs that are more reliable and efficient gt Incorporate features that require hooks into OS Eg concurrency signal handlers Not just a course for dedicated hackers gtWe bring out the hidden hacker in everyone Cover material in this course that you won t see elsewhere gt Linking loading signals gt If nothing else this course will teach you how to make effective use of debuggers such as gdb Course Perspective Most Systems Courses are BuilderCentric Computer Architecture gt Design pipelined processor Operating Systems gt Implement portions of operating system Compilers gt Write compiler for simple language Networking gt Implement and simulate network protocols Relationship to other courses Prerequisites C or better CS 211 Computer Science II ECE 301l303l331 Digital Logic CS 112 211 310 have migrated to using Java instead of C CS 265 Assembly programming no longer taught Goal of this course CS 367 is to replace CS 265 Assembly Programming and expose students to a different programming language C rom a bottom up perspective Programming assignments involving machine and assembly language x86 and programming in C Textbooks Randal E Bryant and David R O Hallaron Computer Systems A Programmer s Perspective Prentice Hall 2003 csappcscmuedu Brian Kernighan and Dennis Ritchie The C Programming Language Second Edition Prentice Hall 1988 You can use any book on C Programming in C Assumption You are comfortable programming in Java andor C C is a procedural imperative programming language Topics C Standard llO library for inputoutput Bitlevel operators Pointers amp Structures Memory allocation and deallocation Assignment HW1 Write a nontrivial program in C Course Outline Programming in C 2 weeks Data Representation 2 weeks Program Representation 5 weeks Linking 1 week Exceptional Control Flow amp Virtual Memory 3 weeks Machinelevel Representation of Data and Programs Topics Bits operations arithmetic assembly language programs representation of C control and data structures Includes aspects of of architecture and compilers Assignments Lab1 Manipulating bits Lab2 Defusing a binary bomb Lab3 Hacking a buffer bomb Linking and Exceptional Control Flow Topics Object files static and dynamic linking libraries loading Hardware exceptions processes process control Unix signals nonlocal jumps Virtual Memory Includes aspects of compilers OS and architecture Assignments Lab4 optional Writing your own shell with job control Logistics Grading Homeworks 15 and Lab Assignments 35 gt can work in groups of two for homeworks gt will be able to work in groups of two for later programming assignments gt All programs will be submitted and tested on a Linux platform for grading You need to obtain an TampE Unix Cluster account See syllabus Midterm 25 amp Final 25 Rationale for Assignments Each assignment should have a welldefined goal such as solving a puzzle or winning a contest Defusing a binary bomb Doing an assignment should result in new skills and concepts Lab1 computer arithmetic digital logic Lab23 assembly language using a debugger understanding the stack Lab4 understanding Unix process control and signals Cheating What is cheating Sharing code either by copying retyping looking at or supplying a copy of a file What is NOT cheating Helping others use systems or tools Helping others with highlevel design issues Helping others debug their code Penalty for cheating Removal from course with failing grade


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

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

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!"

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!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

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.