Computing Science (CMPUT) 201

Size: px
Start display at page:

Download "Computing Science (CMPUT) 201"

Transcription

1 Computing Science (CMPUT) 201 Practical Programming Methodology Paul Lu Department of Computing Science University of Alberta Original material Copyright Some material from other instructors (e.g., Piotr Rudnicki) and sources. Fall 2007

2 Outline Key Points Preparing for Labs Overview Part I 1 Key Points 2 Preparing for Labs 3 Overview

3 Key Points Key Points Preparing for Labs Overview Keep in mind: 1 The course has an emphasis on C (not C++) under Unix. 2 Some C++ topics will be covered. 3 Three assignments. Each assignment builds upon earlier ones. 4 Collaboration (within limits) allowed on assignments. Read the fine print on course policy. 5 There is a lab examination.

4 Labs and Accounts Key Points Preparing for Labs Overview Labs start next week, September 10. NEW: There are lab exercises worth marks! Make sure that: 1 Before your lab, get your Unix accounts from Lab Admin and log in. Bring your ONE card Read and sign the Conditions of Use 2 Go before your lab time. Try to log in beforehand. 3 Bring your King and Sobell textbooks to your labs

5 Goals of Key Points Preparing for Labs Overview Goals: 1 Teach the C programming language and model syntax, memory, debugging, execution 2 Teach the Unix programming model standard in-out-error, pipes, basic API 3 Teach some, practical aspects of programming methodology common modularization techniques, value of simplicity, assertions, source code version control Non-Goals: 1 We assume knowledge of abstraction and object-oriented design 2 We assume you know Java

6 How to succeed in Key Points Preparing for Labs Overview 1 Be fearless in just trying it out. It is hard to do any permanent damage, if you use backups and version control. Write small programs to test out concepts 2 Learn to find the answers for yourself. Your textbooks are excellent resources man pages are your friend Google your compiler error messages the Web knows (almost) all 3 Learn how to use the debugger.

7 How to fail/drown in Key Points Preparing for Labs Overview NOTE: The following points are intended to be ironic. 1 Continue to do things (i.e., write and debug) programs just as you have always done. 2 Wait more than a year between taking CMPUT 115 to. 3 Do not learn how to use the debugger. 4 Do not take advantage of labs to ask questions of your TAs 5 Take 201 because I am interested in learning a bit more about how programming is done. In fact, 201 is intended to help you master programming in C under Unix. 201 is about doing art and not art appreciation.

8 Major Themes in Key Points Preparing for Labs Overview 1 Often, there s more than one way to do something. Have a good set of tools and techniques. If all you have is a hammer, then everything looks like a nail." 2 Clear and simple should be preferred over clever and complex. 3 The difference between spending 10 hours vs. 100 hours on an assignment will come down to best practices. debugger, makefiles, assertions, throw away test programs, incremental testing, automating repetitive tasks start assignments on-time Try to understand what you are doing, instead of just getting something to work.

9 Outline Part II Vertical Strip Running, Compiling Find Double Word Makefiles First Examples Compiler Warnings Other Examples popen: Child Processes Buffer File Contents 4 Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings 5 Other Examples popen: Child Processes Buffer File Contents

10 Vertical Strips Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents It would take years to develop a broad knowledge of Unix and C Vertical strips are examples that cut deeply through many different layers of abstraction, but in a shallow way at each layer Fill out the details by consulting references and through experience We depend on you to read, try, do, and ask your way to a mastery of the material.

11 A Vertical Strip Example: Running Programs Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -lt total 96 -rw paullu prof Sep 6 15:42 sketchpad -rw paullu prof 170 Sep 6 15:41 example.a1.sketchpad paullu@ug30:~/c201>chmod +x./sketchpad paullu@ug30:~/c201>ls -lt total 96 -rwx paullu prof Sep 6 15:42 sketchpad* -rw paullu prof 170 Sep 6 15:41 example.a1.sketchpad paullu@ug30:~/c201>./sketchpad < example.a1.sketchpad NOTE: For all the notes, file sizes and timestamps may differ from reality. 1 The Unix shell (e.g., bash, tcsh) prompts the user for commands to execute with paullu@ug30 2 wget, ls, and sketchpad are all programs executed from the command line of the shell. Unix is often used via the command-line interface

12 man pages Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Manual (man) pages are the traditional, on-line documents for Unix. man wget: details for a specific program man -k http: does a (lame) search using http as keyword man man: details how to use man Often, Unix commands have esoteric command-line options. For example, ls -lt. ls: the list directory contents program -l: long listing format -t: sort by the timestamp

13 Compiling Programs Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -lt total 100 -rw paullu prof 2072 Sep 7 00:17 finddw.c paullu@ug30:~/c201>gcc -Wall -ansi finddw.c -o finddw...snip (some compiler warnings)... paullu@ug30:~/c201>ls -lt total 116 -rwx paullu prof Sep 7 00:19 finddw* -rw paullu prof 2072 Sep 7 00:17 finddw.c 1 Suppose you have a C program in file finddw.c (for find double word ) 2 A program is compiled using a compiler, such as gcc 3 -Wall -ansi are command-line options for gcc. They are also called compiler options. 4 -o finddw specifies the name of the executable file. Default name is a.out

14 Running Find Double Word Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents finddw.test Sometimes, it is is easy to write the same word twice twice and not make a spelling mistake. paullu@ug30:~/c201>./finddw finddw.test In file finddw.test, repeated word: is is Context: easy to Re-run program after fixing!!! In file finddw.test, repeated word: twice twice Context: and not make a spelling mistake. Re-run program after fixing!!! paullu@ug30:~/c201>cat finddw.ok This file is fine. There is nothing to worry about. paullu@ug30:~/c201>./finddw finddw.ok paullu@ug30:~/c201> cat is a program to send the contents of a file to the terminal finddw knows which file to use from the command-line argument

15 Find Double Word Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents finddw.c #include <stdio.h> #include <string.h> /* For strncmp(), etc. */ #define MIN_BUF 256 #define MAX_BUF 2048 char Buffer[ MAX_BUF ]; char Word[ MIN_BUF ]; char NextWord[ MIN_BUF ]; void parsefile( FILE * fp, char * fname ); (code listing continues on later slides) Before the executable code, a best practice is to list: header files (#include) (macro) definitions (#define) global variables function prototypes

16 Find Double Word (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents int main( int argc, char * argv[] ) int i; FILE * fp; for( i = 1; i < argc; i++ ) fp = fopen( argv[ i ], "r" ); if( fp == NULL ) printf( "Could not open file %s\n", argv[ i ] ); exit( -1 ); } else } } return( 0 ); } /* main */ parsefile( fp, argv[ i ] ); fclose( fp ); (code listing continues on later slides) The main() function is where the program starts executing. The Unix shell finds the executable and starts running it at function main(). main() is a function, not a method. But, it has similar syntax in its function definition compared to Java.

17 Find Double Word (3) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents int main( int argc, char * argv[] ) int i; FILE * fp; for( i = 1; i < argc; i++ ) fp = fopen( argv[ i ], "r" ); if( fp == NULL ) printf( "Could not open file %s\n", argv[ i ] ); exit( -1 ); } else parsefile( fp, argv[ i ] ); fclose( fp ); } } return( 0 ); } /* main */ (code listing continues on later slides) Local variables (e.g., int i, FILE * fp) are defined before being used For loops (e.g., for(... )) are similar to Java Control flow (e.g., if()... else) is similar to Java

18 Find Double Word (4) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents int main( int argc, char * argv[] ) int i; FILE * fp; for( i = 1; i < argc; i++ ) fp = fopen( argv[ i ], "r" ); if( fp == NULL ) printf( "Could not open file %s\n", argv[ i ] ); exit( -1 ); } else parsefile( fp, argv[ i ] ); fclose( fp ); } } return( 0 ); } /* main */ (code listing continues on later slides) function calls (e.g., fopen(), parsefile(), fclose()) are similar to Java C input/output is by the Standard I/O (stdio) library (e.g., printf())

19 Find Double Word (5) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void parsefile( FILE * fp, char * fname ) int rval; /* Read first word */ rval = fscanf( fp, "%s", Word ); if( rval!= 1 ) printf( "Failed to read first word\n" ); exit( -1 ); } (code listing continues on later slides) comments should be used (e.g., /* Read first word */) to explain the semantics, not the syntax 90% of the time, clear code that follows standard conventions is preferred over clever code C input is by the Standard I/O (stdio) library (e.g., fscanf())

20 Find Double Word (6) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents while(! feof( fp ) ) rval = fscanf( fp, "%s", NextWord ); if( rval!= 1 ) continue; if( strncmp( Word, NextWord, MIN_BUF ) == 0 ) printf( "In file %s, repeated word: %s %s\n", fname, Word, NextWord ); } /* Heuristic as to when to print out context info */ /* First letter must be alphabets */ if( isalpha( Word[ 0 ] ) ) fgets( Buffer, MAX_BUF, fp ); printf( "Context: %s\n", Buffer ); printf( "Re-run program after fixing!!!\n " ); } strncpy( Word, NextWord, MIN_BUF ); } /* while */ } /* parsefile */ While loops (e.g., while(... )) are similar to Java C strings are handled using a family of functions (e.g., strncmp(), strncpy())

21 Makefiles Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile # A simple makefile finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw paullu@ug30:~/c201>make gcc -Wall -ansi finddw.c -o finddw 1 By default, the program make looks for Makefile or makefile (which are text files). 2 Makefiles are examples of declarative programs: You tell the system what you want, more than how to achieve it. In truth, it is a hybrid of declarative and imperative. 3 First Common Pitfall: The white space in front of gcc -Wall... is actually an invisible tab.

22 Makefiles (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile # A simple makefile finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw paullu@ug30:~/c201>make gcc -Wall -ansi finddw.c -o finddw 1 finddw: finddw.c: 1 Defines a makefile target (i.e., finddw) and its (list of) dependencies (i.e., finddw.c) (aka prerequisite-list). 2 A makefile can have multiple targets. 3 The dependencies can be files, or other targets. 2 TAB gcc -Wall -ansi finddw.c -o finddw 1 Defines an action (aka construction-commands). 2 Actions are anything that you can do from the Unix command line.

23 Make Execution Model Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile # A simple makefile finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw paullu@ug30:~/c201>make gcc -Wall -ansi finddw.c -o finddw 1 In this example, make and make finddw have the same effect. 2 When you execute make 1 Make looks for a makefile. 2 Make looks for your target (e.g., finddw) or uses the first one by default. 3 Make looks at the timestamps (cf. ls -lt) on the target and the dependencies. 4 If the target is more recent than the dependencies, then make does nothing more.

24 Make Execution Model (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile # A simple makefile finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw paullu@ug30:~/c201>make gcc -Wall -ansi finddw.c -o finddw 1 If the target is less recent than the dependencies, or if the target does not exist, then make invokes the targets for the dependencies (if any). 2 Then, make invokes the actions for the current target. 3 Second Common Pitfall: It is easy to forget a dependency for a target, especially when refactoring code. Solution: Be careful. And, have a make clean target, as discussed below.

25 Make Execution Model (3) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents gcc -Wall -ansi finddw.c -o finddw make: finddw is up to date. finddw.c gcc -Wall -ansi finddw.c -o finddw which which: shell built-in command. touch /usr/bin/touch 1 touch is a Unix command that updates the timestamp of a file to, for example, simulate editing a file. The contents of the file does not change. 2 Notice how make s declarative execution model only looks at timestamps, and does not look at the contents of a file. 3 which is a Shell command to tell you where (or which) an executable is located

26 Make Execution Model (4) Vertical Strip Running, Compiling Makefile.v2 finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw Find Double Word Makefiles Compiler Warnings clean: -rm *.o finddw Other Examples popen: Child Processes Buffer File Contents tar: tar cvf submit.tar finddw.c Makefile README Makefiles are useful for more than just building programs. Anything that can be automated as a sequence of actions and/or targets and dependencies can be automated via a Makefile. Target clean is a common target (and required in your assignments). Note that you should never have a file with the name clean.

27 Make Execution Model (5) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile.v2 finddw: finddw.c gcc -Wall -ansi finddw.c -o finddw clean: tar: -rm *.o finddw tar cvf submit.tar finddw.c Makefile README The -rm... removes files that can be (and should be) re-created from other files. For example,.o files are created from.c files (more later). For example, executable finddw is created from.c files. The - in front of rm says, If the action should fail in any way, continue with the next action

28 Make Execution Model (6) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -f Makefile.v2 clean rm *.o finddw rm: cannot remove *.o : No such file or directory make: [clean] Error 1 (ignored) paullu@ug30:~/c201>make -f Makefile.v2 gcc -Wall -ansi finddw.c -o finddw paullu@ug30:~/c201>touch README paullu@ug30:~/c201>make -f Makefile.v2 tar tar cvf submit.tar finddw.c Makefile README finddw.c Makefile README 1 Target tar automates the error-prone command to create a tape archive (tar) file. The cvf command-line options say: create a new tar file, be verbose when doing so, and use the filename that follows immediately after the cvf (i.e., submit.tar). After the cvf submit.tar is the list of files to put into the tar file. 2 Common Pitfall: It is a big mistake to do something like: tar cvf finddw.c Makefile README.

29 Make Execution Model (7) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile.v3 finddw: finddw.o gcc -Wall -ansi finddw.o -o finddw finddw.o: finddw.c gcc -Wall -ansi -c finddw.c clean: -rm *.o finddw tar: tar cvf submit.tar finddw.c Makefile README -f Makefile.v3 finddw.o gcc -Wall -ansi -c finddw.c -lt *.o -rw paullu prof 2020 Sep 11 18:09 finddw.o paullu@ug30:~/c201>make -f Makefile.v3 finddw gcc -Wall -ansi finddw.o -o finddw paullu@ug30:~/c201>ls -lt finddw* -rwx paullu prof Sep 11 18:09 finddw* -rw paullu prof 2020 Sep 11 18:09 finddw.o -rw paullu prof 2072 Sep 11 16:35 finddw.c -rw paullu prof 52 Sep 9 01:15 finddw.ok -rw paullu prof 93 Sep 9 01:08 finddw.test paullu@ug30:~/c201>make -f Makefile.v3 clean rm *.o finddw paullu@ug30:~/c201>make -f Makefile.v3 gcc -Wall -ansi -c finddw.c gcc -Wall -ansi finddw.o -o finddw paullu@ug30:~/c201>

30 Make Execution Model (8) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Makefile.v3 finddw: finddw.o gcc -Wall -ansi finddw.o -o finddw finddw.o: finddw.c gcc -Wall -ansi -c finddw.c clean: -rm *.o finddw tar: tar cvf submit.tar finddw.c Makefile README -f Makefile.v3 finddw.o gcc -Wall -ansi -c finddw.c -lt *.o -rw paullu prof 2020 Sep 11 18:09 finddw.o paullu@ug30:~/c201>make -f Makefile.v3 finddw gcc -Wall -ansi finddw.o -o finddw...snip... The gcc -Wall -ansi -c illustrates separate compilation in C.

31 Compiler Warnings Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -11 finddw.c #include <stdio.h> #include <string.h> /* For strncmp(), etc. */ #define MIN_BUF 256 #define MAX_BUF 2048 char Buffer[ MAX_BUF ]; char Word[ MIN_BUF ]; char NextWord[ MIN_BUF ]; void parsefile( FILE * fp, char * fname ); paullu@ug30:~/c201>make gcc -Wall -ansi finddw.c -o finddw first.finddw.c: In function main : first.finddw.c:23: warning: implicit declaration of function exit first.finddw.c: In function parsefile : first.finddw.c:62: warning: implicit declaration of function isalpha 1 As discussed earlier, the finddw program will generate compiler warnings. 2 Warnings are not the same, fatal things as errors. But, good programming style and methodology requires that warnings be fixed.

32 Compiler Warnings (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -2 finddw.c #include <stdio.h> #include <string.h> /* For strncmp(), etc. */ gcc -Wall -ansi finddw.c -o finddw first.finddw.c: In function main : first.finddw.c:23: warning: implicit declaration of function exit first.finddw.c: In function parsefile : first.finddw.c:62: warning: implicit declaration of function isalpha paullu@ug30:~/c201>cat -n finddw.c grep "^ *23" 23 exit( -1 ); paullu@ug30:~/c201>cat -n finddw.c grep "^ *62" 62 if( isalpha( Word[ 0 ] ) ) 1 The man page for exit() (i.e., man 3 exit) shows that I need #include <stdlib.h>. At the end of man exit, there is a SEE ALSO section that pointed me to exit(3), which is why we need to do man 3 exit. 2 The man page for isalpha() (i.e., man isalpha) shows that I need #include <ctype.h>.

33 Compiler Warnings (3) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -5 finddw.c #include <stdio.h> #include <string.h> /* For strncmp(), etc. */ #include <stdlib.h> /* For exit(), etc. */ #include <ctype.h> /* For isalpha(), etc. */ gcc -Wall -ansi finddw.c -o finddw 1 The warnings have now been fixed. 2 Remember, your main tools for this are: Man pages Google Your textbooks Your TAs, instructor, and fellow students.

34 popen Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents -Wall -ansi testpopen.c hello testpopen.c #include <stdio.h> #include <stdlib.h> /* For exit() */ extern extern FILE *popen(const char *command, const char *type); int pclose(file *stream); int main( int argc, char * argv[] ) FILE * fppo; fppo = popen( "grep hello", "w" ); if( fppo == NULL ) printf( "Error\n" ); exit( -1 ); } fprintf( fppo, "greetings\n" ); fprintf( fppo, "hello\n" ); fprintf( fppo, "good bye\n" ); pclose( fppo ); return( 0 ); } /* main */

35 popen (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents int main( int argc, char * argv[] ) FILE * fppo; fppo = popen( "grep hello", "w" ); if( fppo == NULL ) printf( "Error\n" ); exit( -1 ); } 1 popen (aka process I/O open ) allows you run create a helper, child process to perform a function. There is a corresponding pclose function. 2 Unix is a multiprocessing operating system: different processes (i.e., programs being executed) can run concurrently (i.e., at the same time). 3 This is a powerful abstraction and modularization technique, especially since the programs/processes can be written in any language.

36 popen (3) Vertical Strip Running, Compiling Find Double Word fprintf( fppo, "greetings\n" ); fprintf( fppo, "hello\n" ); fprintf( fppo, "good bye\n" ); pclose( fppo ); return( 0 ); } /* main */ Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents 1 popen returns a FILE * (aka file pointer). This is the same file pointer seen in the finddw example for open files. You can fprintf(), fscanf(), etc. 2 In Unix, many different objects, interfaces, and mechanisms (i.e., a specific abstraction by which to accomplish a task) look like files. Sometimes, the similarity is incomplete; you use pclose() instead of fclose() here. 3 This is a powerful abstraction and modularization technique, especially since the programs/processes can be written in any language.

37 popen (4) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents Also 1 The same ability to combine or pipeline processes can be done from the command line of the shell. This means one can fearlessly try pipelines before incorporating them in one s program. paullu@ug30:~/c201>cat input.file grep hello hello paullu@ug30:~/c201>./a.out hello paullu@ug30:~/c201>cat -n finddw.c grep "^ *63" paullu@ug30:~/c201>grep "popen.*grep" testpopen2.c fppo = popen( "cat -n finddw.c grep \"^ *63\"", "w" ); 2 Depending on what you need to have done, there is also the system() library function for running child processes. system( "cat -n finddw.c grep \"^ *63\"" ); 3 But, what are the disadvantages of concurrent processes and the everything is a file design philosophy?

38 Read a File Into Memory and Buffer Contents Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_BUF 256 /* Max line size */ #define MAX_LINES 32 /* Max number of lines */ struct aline /* A structure for heterogeneous data */ char line[ MAX_BUF ]; int type; }; 1 A struct (or structure) is C s mechanism for heterogeneous, aggregate data structures. 2 The closest thing in Java is a class. Structures are like classes with only public data members. Structures and classes are templates and must be instantiated (aka allocated). But, structures do not have associated methods as part of the structure itself. Abstract data types (ADTs) are created using structures plus other techniques.

39 Structures Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents struct aline /* A structure for heterogeneous data */ char line[ MAX_BUF ]; int type; }; /* This semicolon is necessary */ 1 A struct ends with a semicolon. 2 One refers to the new struct type with struct aline (see the upcoming code). 3 A structure can contain any built-in C type (e.g., int), or arrays, multi-dimensional arrays, or other structures. 4 Yes, you can have arrays of structures (like arrays of objects).

40 Read a File Into Memory (2) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents extern void bufferfile( FILE * fp, struct aline * thelines, int * currentlineptr, int maxlines ); extern void classifyline( struct aline * thelines, int currentline ); extern void printclass( struct aline * thelines, int currentline ); int main( int argc, char * argv[] ) int i; FILE * fp; /* Here, I avoid global variables */ struct aline thelines[ MAX_LINES ]; /* An array of structs */ int currentline; currentline = 0; memset( thelines, 0, sizeof( thelines ) ); /* Initialize. Defensive. */ for( i = 1; i < argc; i++ ) fp = fopen( argv[ i ], "r" ); if( fp == NULL ) printf( "Could not open file %s\n", argv[ i ] ); } else /* currentline is passed-by-reference/pointer */ bufferfile( fp, thelines, &currentline, MAX_LINES ); fclose( fp ); } } return( 0 ); } /* main */

41 Read a File Into Memory (3) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents int main( int argc, char * argv[] ) int i; FILE * fp; /* Here, I avoid global variables */ struct aline thelines[ MAX_LINES ]; /* An array of structs */ int currentline; currentline = 0; memset( thelines, 0, sizeof( thelines ) ); /* Initialize. Defensive. */ 1 Local variables are not initialized automatically. There are no Java-like constructors. 2 Initializing strings is particularly good, defensive programming methodology. Highly recommended best practice. 3 Once you understand the memory model of C and strings, memset() is a quick, easy, and effective way to initialize things. 4 The sizeof() operator is also useful for statically allocated data structures, as we see here.

42 Read a File Into Memory (4) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents /* currentline is passed-by-reference/pointer */ bufferfile( fp, thelines, &currentline, MAX_LINES ); The default for parameter passing is pass-by-value (like Java). But, what value? 1 Arrays and strings (which are arrays) always pass the value of the pointer. They are implicitly pass-by-reference (aka pass-by-pointer). Pass-by-reference is an important way to get data out of a function (aka persistence). 2 For other (smaller) data types, the value of the variable is passed. In this call site example, only MAX_LINES is pass-by-value. 3 But, the programmer can explicitly choose and use pass-by-reference. The parameter &currentline is also an example of pass-by-reference. The function itself has to be expecting pointers, as necessary.

43 Read a File Into Memory (5) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents /* currentline is passed-by-reference/pointer */ bufferfile( fp, thelines, &currentline, MAX_LINES ); 1 In Java, all method parameters are pass-by-value. 2 However, since objects are always accessed via references and handles, changes to an object inside a method affect the actual object. This is like pass-by-reference (of objects) in the C world. 3 Changes to the reference do not affect the original reference since the reference itself is pass-by-value. 4 So, the way C treats arrays (and strings) is analogous to the way Java treats object references. But, for other types, C gives you a choice.

44 Read a File Into Memory (6) Vertical Strip Running, Compiling Find Double Word else } /* currentline is passed-by-reference/pointer */ bufferfile( fp, thelines, &currentline, MAX_LINES ); fclose( fp ); Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents 1 fp is a pointer, despite not having an &, because it is already of type FILE *. It is already a pointer. 2 thelines is a pointer, despite not having an &, because it is of type struct aline thelines[], an array. Thus, thelines is of type struct aline *. But, thelines[ 0 ] is of type struct aline. 3 currentline is an integer, but we turn it into a pointer (just for this function call site) by using the & operator. We ll have lots more to say about C pointers later. 4 Can we use the & operator on MAX_LINES to get a pointer? No. Why not?

45 Read a File Into Memory (7) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void bufferfile( FILE * fp, struct aline * thelines, int * currentlineptr, int maxlines ) char * rbuf; /* Line-oriented */ while( ( *currentlineptr < maxlines ) &&!feof( fp ) ) rbuf = fgets( thelines[ *currentlineptr ].line, MAX_BUF, fp ); if( rbuf == NULL ) break; printf( "Read (%2d): %s", *currentlineptr, thelines[ *currentlineptr ].line ); classifyline( thelines, *currentlineptr ); printclass( thelines, *currentlineptr ); fflush( stdout ); (*currentlineptr)++; } /* while */ /* Warn user if we exceed maximum number of lines buffered */ if( *currentlineptr >= maxlines ) printf( "Warning: Exceeded %d lines of buffering.\n", } } /* bufferfile */ *currentlineptr);

46 Read a File Into Memory (8) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void bufferfile( FILE * fp, struct aline * thelines, int * currentlineptr, int maxlines )...snip... } /* bufferfile */ 1 If a parameter is supposed to be a pointer, it always has the form with * or []. fp, thelines, currentlineptr Note that [] is just another way to say *, which is why char * argv[] and char ** argv are the same!

47 Read a File Into Memory (9) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents /* Line-oriented */ while( ( *currentlineptr < maxlines ) &&!feof( fp ) ) rbuf = fgets( thelines[ *currentlineptr ].line, MAX_BUF, fp ); if( rbuf == NULL ) break; printf( "Read (%2d): %s", *currentlineptr, thelines[ *currentlineptr ].line ); classifyline( thelines, *currentlineptr ); printclass( thelines, *currentlineptr ); fflush( stdout ); (*currentlineptr)++; } /* while */ /* Warn user if we exceed maximum number of lines buffered */ if( *currentlineptr >= maxlines ) printf( "Warning: Exceeded %d lines of buffering.\n", *currentlineptr); } 1 In Java, object references are implicitly dereferenced. 2 In C, pointers are explicitly dereferenced by an operator. 3 Pointers must be dereferenced using either *, [] (or ->).

48 Read a File Into Memory (10) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents while( ( *currentlineptr < maxlines ) &&!feof( fp ) ) rbuf = fgets( thelines[ *currentlineptr ].line, MAX_BUF, fp ); if( rbuf == NULL ) break; printf( "Read (%2d): %s", *currentlineptr, thelines[ *currentlineptr ].line ); classifyline( thelines, *currentlineptr ); printclass( thelines, *currentlineptr ); fflush( stdout ); (*currentlineptr)++; } /* while */ 1 Pointers are a source of great programming power and great programming errors. 2 The compiler can do simple type checking. paullu@ug30:~/c201>grep while.*currentlineptr bufferfile.c while( ( currentlineptr < maxlines ) &&!feof( fp ) ) paullu@ug30:~/c201>make gcc -Wall -ansi bufferfile.c -o bufferfile bufferfile.c: In function bufferfile : bufferfile.c:53: warning: comparison between pointer and integer 3 But, it was only a warning. The executable was still created!

49 Read a File Into Memory (11) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents /* In main() */ /* currentline is passed-by-reference/pointer */ bufferfile( fp, thelines, &currentline, MAX_LINES );...snip... while( ( *currentlineptr < maxlines ) &&!feof( fp ) ) rbuf = fgets( thelines[ *currentlineptr ].line, MAX_BUF, fp ); if( rbuf == NULL ) break; printf( "Read (%2d): %s", *currentlineptr, thelines[ *currentlineptr ].line ); classifyline( thelines, *currentlineptr ); printclass( thelines, *currentlineptr ); fflush( stdout ); (*currentlineptr)++; } /* while */ 1 *currentlineptr: The value of currentline in main() 2 thelines[ *currentlineptr ]: The array thelines in main(), at index currentline in main()

50 Read a File Into Memory (12) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents while( ( *currentlineptr < maxlines ) &&!feof( fp ) ) rbuf = fgets( thelines[ *currentlineptr ].line, MAX_BUF, fp ); if( rbuf == NULL ) break; printf( "Read (%2d): %s", *currentlineptr, thelines[ *currentlineptr ].line ); classifyline( thelines, *currentlineptr ); printclass( thelines, *currentlineptr ); fflush( stdout ); (*currentlineptr)++; } /* while */ 1 Dot operator: thelines[ *currentlineptr ].line: A field line in array thelines in main(), at index currentline in main(). 2 fflush( stdout ); forces the output of printf() to standard out. 3 (*currentlineptr)++; increments the value of currentline in main(). The dereferencing happens before the increment.

51 Read a File Into Memory (13) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void classifyline( struct aline * thelines, int currentline ) int rval; char firstword[ MAX_BUF ]; #if 0 #endif thelines[ currentline ].type = -1; /* Default */ /* Check for comments */ if( thelines[ currentline ].line[ 0 ] == # ) thelines[ currentline ].type = 0; return; } /* Check for matrix definitions */ memset( firstword, 0, MAX_BUF ); /* Initialize. Defensive. */ rval = sscanf( thelines[ currentline ].line, "%s", firstword ); if( rval!= 1 ) printf( "Error in sscanf\n" ); return; } if( strncmp( firstword, "Matrix", 6 ) ) == 0 ) thelines[ currentline].type = 1; } } /* classifyline */

52 Read a File Into Memory (14) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void classifyline( struct aline * thelines, int currentline ) int rval; char firstword[ MAX_BUF ]; thelines[ currentline ].type = -1; /* Default */ /* Check for comments */ if( thelines[ currentline ].line[ 0 ] == # ) thelines[ currentline ].type = 0; return; } 1 Having a default value of -1 for type is good, defensive programming and a best practice. 2 thelines[ currentline ].line[0] == # Refers to the first character of field line of the structure at index currentline, in the array thelines in main() # (single quotes) is a character constant, not a string. == can be used compare characters, but not strings 3 return returns in the middle of the function

53 Read a File Into Memory (15) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents #if 0 #endif /* Check for matrix definitions */ memset( firstword, 0, MAX_BUF ); /* Initialize. Defensive. */ rval = sscanf( thelines[ currentline ].line, "%s", firstword ); if( rval!= 1 ) printf( "Error in sscanf\n" ); return; } if( strncmp( firstword, "Matrix", 6 ) ) == 0 ) thelines[ currentline].type = 1; } 1 Always zero ing a string (i.e., firstword) is good, defensive programming and a best practice. 2 sscanf() allows parsing from a string buffer. scanf() gets its input from standard in fscanf() gets its input from a file, via a file pointer 3 We use sscanf() to automatically handle white space issues

54 Read a File Into Memory (16) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents #if 0 #endif /* Check for matrix definitions */ memset( firstword, 0, MAX_BUF ); /* Initialize. Defensive. */ rval = sscanf( thelines[ currentline ].line, "%s", firstword ); if( rval!= 1 ) printf( "Error in sscanf\n" ); return; } if( strncmp( firstword, "Matrix", 6 ) ) == 0 ) thelines[ currentline].type = 1; } 1 #if 0 and #endif are examples of conditional compilation. Here, it means do not include the printf() line. Use this technique for your own debugging output; see assignment description. 2 Frankly, hard-coding the 6 for the strncmp() is not the best idea. It is OK and used for simplicity here.

55 Read a File Into Memory (17) Vertical Strip Running, Compiling Find Double Word Makefiles Compiler Warnings Other Examples popen: Child Processes Buffer File Contents void printclass( struct aline * thelines, int currentline ) switch( thelines[ currentline ].type ) case -1: printf( "\tunknown\n" ); break; case 0: printf( "\tcomment\n" ); break; case 1: printf( "\tmatrix Definition\n" ); break; default: printf( "\tundefined\n" ); break; } } /* printclass */ Best practices: 1 Always have a default: label. 2 Make you you have a break: at the end of each case, unless you really, really mean it. And, then add a comment.

56 Outline Part III Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization Language 6 Language (1) Thinking in C Memory Model Arrays and Strings in Memory 7 Language (2) Linked Lists Multidimensional Arrays 8 Language (3) Storage and Scope Function Pointers Initialization

57 Thinking in C vs. Java Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization There are a number of differences that require a new way of thinking. C is sometimes known as a portable, high-level assembly language and is often used to write operating systems, database management systems, graphics systems because C allows you to have: 1 power: manage and manipulate memory down to a single bit, or access I/O devices 2 performance: have a simple mapping from C construct to execution model 3 understandability: does not have (many) hidden overheads and side effects 4 functionality: many libraries and good support on Unix

58 Thinking in C vs. Java (2) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization But, with power comes more responsibility for the programmer: 1 C does not have automatic initialization/finalization via constructors/destructors 2 C does not have automatic array bounds checking 3 C does not have garbage collection 4 C will let you bypass type checking, both explicitly and implicitly 5 C will let you modify any part of the user s address space The programmer must learn the model, the best practices, and the standard toolset (e.g., debuggers) C can be used for any kind of programming. But, it is not the best choice for all kinds of applications. We all need to know C because of all the C code out there, including Linux, compilers (e.g., gcc), etc.

59 Thinking in C vs. Java (3) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 1 Instead of Java s objects, think of C s structures and abstract data types (ADT) 2 Instead of Java s class methods, think of C s functions with similar parameter types (e.g., FILE * for fprintf(), fscanf()) 3 Instead of Java s method overloading, think of C s functions with different but similar names (e.g., scanf(), fscanf(), sscanf()) 4 Instead of Java s string class, think of C s arrays of memory and buffers used to hold characters and other data 5 Instead of Java s garbage collection, think of C s free(), fclose(), pclose(), etc.

60 Thinking in C vs. Java (4) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 6 Instead of Java s object references, think of C s pointers to anything 7 Instead of Java s exceptions, think of a C function s return value and the global variable errno 8 Instead of Java s import feature for packages, think of C s header files (i.e., #include) and linking to libraries 9 Instead of Java s virtual machine, think of C s execution model and address space organization 10 Instead of Java s libraries, think of C s libraries and Unix system calls

61 Thinking in C vs. Java (5) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 11 Instead of Java s boolean FALSE and TRUE, think of C s interpretation of zero and non-zero values. (NOTE: C99 does have a bool type.) 12 Instead of Java s new and garbage collection, think of C s library functions malloc(), calloc(), and free() 13 Instead of Java s inheritance, think of C s???? Wrappers?? 14 Instead of Java s polymorphism, think of C s???? Function pointers?? Actually, one can write in an OO style (including any design pattern) in C. But, it is often non-obvious or much more complicated.

62 A Process s Address Space Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization A process is a program being executed. The von Neumann model includes the notion that code and data are stored in a common memory. We call that an address space. Each process (usually) has a separate address space. The key parts of an address space include: 1 Program text segment: The executable code written by the user and library code (e.g., main() and printf()) 2 Global data segment: Global variables and constants, including string constants (e.g, char * str = "Hello") 3 Heap segment: For dynamic memory management, such as malloc() 4 Stack segment: For local variables, function parameters, and tracking nested functions calls and recursion

63 A Process s Address Space (2) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope 0xffffffff High Memory: 4 GB Kernel Space Stack Heap Data Stack segment: Local variables, function parameters, support for function calls Grows from high to low memory Heap segment: Dynamic memory, malloc() Grows from low to high memory Function Pointers Initialization 0x Text Kernel Space Low Memory: 0 Global data segment: Global variables and constants Program text segment: Code

64 A Process s Address Space (3) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization We also distinguish between: 1 User space: parts of memory that can be accessed by normal programs 1 The user s code and data 2 Library code and data 2 Kernel or OS space: parts of memory that can only be accessed by the operating system A segmentation fault refers to an inappropriate access to a part of memory, usually due to a wrong pointer or overflowing a buffer. And, we distinguish between: 1 Physical memory: RAM chips 2 Logical memory: An illusion of memory provided by the OS (a big topic in CMPUT 379)

65 A Process s Address Space (4) NOTE: Numbers may vary. Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) 0xffffffff High Memory: 4 GB Kernel Space Stack paullu@ug30:~/c201>cat t1.c #include <stdio.h> char Buffer[ 8 ]; int GlobalI; int main( int argc, char * argv[] ) int locali; Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 0x Heap Data Text Kernel Space Low Memory: 0 printf( "Buffer = %p / %u\n", Buffer, (int)buffer ); printf( "GlobalI = %p / %u\n", &GlobalI, (int)&globali ); printf( "locali = %p / %u\n", &locali, (int)&locali ); printf( "&(Buffer[ 7 ]) = %p / %u\n", &(Buffer[7]), (int)&(buffer[7]) ); return( 0 ); } /* main */ paullu@ug30:~/c201>gcc -Wall -ansi t1.c paullu@ug30:~/c201>./a.out Buffer = 0x / GlobalI = 0x / locali = 0xbffffa94 / &(Buffer[ 7 ]) = 0x /

66 A Process s Address Space (5) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 0xffffffff 0x High Memory: 4 GB Kernel Space Stack Heap Data Text Kernel Space Low Memory: 0 #include <stdio.h> int GlobalI; void sub() int locali; printf( "sub (locali) = %p / %u\n", &locali, (int)&locali ); } /* sub */ int main( int argc, char * argv[] ) int locali; printf( "main(locali) = %p / %u\n", &locali, (int)&locali ); sub(); printf( "GlobalI = %p / %u\n", &GlobalI, (int)&globali ); printf( "main() = %p / %u\n", main, (int)main ); printf( "sub() = %p / %u\n", sub, (int)sub ); return( 0 ); } /* main */ paullu@ug30:~/c201>./a.out main(locali) = 0xbffffa94 / sub (locali) = 0xbffffa84 / GlobalI = 0x80496cc / main() = 0x80483a4 / sub() = 0x /

67 A Process s Address Space (6) 0xffffffff High Memory: 4 GB Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization Kernel Space Stack Heap Data Text #include <stdio.h> #include <stdlib.h> void sub( char * str ) printf( "&str = %p / %u\n", &str, (int)&str ); printf( " str = %p / %u\n", str, (int)str ); } /* sub */ int main( int argc, char * argv[] ) char * str; char * str2 = "Hello"; printf( "&str = %p / %u\n", Kernel Space &str, (int)&str ); 0x Low Memory: 0 printf( " str = %p / %u\n", str, (int)str ); str = malloc( 16 ); paullu@ug30:~/c201>./a.out printf( " str = %p / %u\n", &str = 0xbffffa94 / str, (int)str ); str = 0xbffffaf4 / printf( " str2 = %p / %u\n", str = 0x / str2, (int)str2 ); str2 = 0x80485c9 / sub( str ); &str = 0xbffffa80 / return( 0 ); str = 0x / } /* main */

68 Arrays and Strings in Memory Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 0xffffffff High Memory: 4 GB Kernel Space Stack str 0xbffffa94 0xbffffaf4 (junk!) Heap Data Text Kernel Space 0x Low Memory: 0 Focusing on str paullu@ug30:~/c201>cat t4.c #include <stdio.h> #include <stdlib.h> #include <assert.h> /* New */ int main( int argc, char * argv[] ) char * str; char * str2 = "Hello"; printf( "&str = %p / %u\n", &str, (int)&str ); printf( " str = %p / %u\n", ---> str, (int)str ); str = malloc( 16 ); assert( str!= NULL ); /* New */ printf( " str = %p / %u\n", str, (int)str ); printf( " str2 = %p / %u\n", str2, (int)str2 ); return( 0 ); } /* main */ paullu@ug30:~/c201>gcc -Wall -ansi t4.c paullu@ug30:~/c201>./a.out &str = 0xbffffa94 / str = 0xbffffaf4 / str = 0x / str2 = 0x80485c4 /

69 Arrays and Strings in Memory (2) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization 0x xffffffff str 0xbffffa94 str2 0xbffffa40 0x080485c4 0x High Memory: 4 GB Kernel Space Stack 0x x080485c4 Heap Hello\0 Text Kernel Space Low Memory: 0 Data paullu@ug30:~/c201>cat t4.c #include <stdio.h> #include <stdlib.h> #include <assert.h> /* New */ int main( int argc, char * argv[] ) char * str; char * str2 = "Hello"; printf( "&str = %p / %u\n", &str, (int)&str ); printf( " str = %p / %u\n", str, (int)str ); str = malloc( 16 ); assert( str!= NULL ); /* New */ printf( " str = %p / %u\n", str, (int)str ); printf( " str2 = %p / %u\n", str2, (int)str2 ); return( 0 ); } /* main */ paullu@ug30:~/c201>gcc -Wall -ansi t4.c paullu@ug30:~/c201>./a.out &str = 0xbffffa94 / str = 0xbffffaf4 / str = 0x / str2 = 0x80485c4 /

70 Arrays and Strings in Memory (3) Language (1) Thinking in C Memory Model Arrays and Strings in Memory Language (2) Linked Lists Multidimensional Arrays Language (3) Storage and Scope Function Pointers Initialization str 0xbffffa94 str2 0xbffffa40 0x080497a7 0x x x080485c9 0x080485c8 0x080485c7 0x080485c6 0x080485c5 0x080485c4 0x x080485c4 \0 o l l e H paullu@ug30:~/c201>cat t4.c #include <stdio.h> #include <stdlib.h> #include <assert.h> /* New */ int main( int argc, char * argv[] ) char * str; char * str2 = "Hello"; printf( "&str = %p / %u\n", &str, (int)&str ); printf( " str = %p / %u\n", str, (int)str ); str = malloc( 16 ); assert( str!= NULL ); /* New */ printf( " str = %p / %u\n", str, (int)str ); printf( " str2 = %p / %u\n", str2, (int)str2 ); return( 0 ); } /* main */ paullu@ug30:~/c201>gcc -Wall -ansi t4.c paullu@ug30:~/c201>./a.out &str = 0xbffffa94 / str = 0xbffffaf4 / str = 0x / str2 = 0x80485c4 /

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: C and Unix Overview This course is about computer organization, but since most of our programming is

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview Computer Science 322 Operating Systems Mount Holyoke College Spring 2010 Topic Notes: C and Unix Overview This course is about operating systems, but since most of our upcoming programming is in C on a

More information

Kurt Schmidt. October 30, 2018

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

More information

C for C++ Programmers

C for C++ Programmers C for C++ Programmers CS230/330 - Operating Systems (Winter 2001). The good news is that C syntax is almost identical to that of C++. However, there are many things you're used to that aren't available

More information

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and #include The Use of printf() and scanf() The Use of printf()

More information

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

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

More information

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

PRINCIPLES OF OPERATING SYSTEMS

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

More information

Lecture 03 Bits, Bytes and Data Types

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

More information

Short Notes of CS201

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

More information

CS201 - Introduction to Programming Glossary By

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

More information

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut mith College CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 2 Hours D. Thiebaut Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to Assembly Unix Standard

More information

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes COMP26120: Algorithms and Imperative Programming Lecture 5: Program structuring, Java vs. C, and common mistakes Lecture outline Program structuring Functions (defining a functions, passing arguments and

More information

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

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-43 Exam Review February, 01 Presented by the RIT Computer Science Community http://csc.cs.rit.edu C Preprocessor 1. Consider the following program: 1 # include 3 # ifdef WINDOWS 4 # include

More information

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

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

More information

Project 2: Shell with History1

Project 2: Shell with History1 Project 2: Shell with History1 See course webpage for due date. Submit deliverables to CourSys: https://courses.cs.sfu.ca/ Late penalty is 10% per calendar day (each 0 to 24 hour period past due). Maximum

More information

Recitation 2/18/2012

Recitation 2/18/2012 15-213 Recitation 2/18/2012 Announcements Buflab due tomorrow Cachelab out tomorrow Any questions? Outline Cachelab preview Useful C functions for cachelab Cachelab Part 1: you have to create a cache simulator

More information

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

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

More information

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

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

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14 APT Session 4: C Laurence Tratt Software Development Team 2017-11-10 1 / 14 http://soft-dev.org/ What to expect from this session 1 C. 2 / 14 http://soft-dev.org/ Prerequisites 1 Install either GCC or

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

CSE 374 Programming Concepts & Tools

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

More information

Lecture 7: file I/O, more Unix

Lecture 7: file I/O, more Unix CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 7: file

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

CSCI 2132 Final Exam Solutions

CSCI 2132 Final Exam Solutions Faculty of Computer Science 1 CSCI 2132 Final Exam Solutions Term: Fall 2018 (Sep4-Dec4) 1. (12 points) True-false questions. 2 points each. No justification necessary, but it may be helpful if the question

More information

MPATE-GE 2618: C Programming for Music Technology. Syllabus

MPATE-GE 2618: C Programming for Music Technology. Syllabus MPATE-GE 2618: C Programming for Music Technology Instructor Dr. Schuyler Quackenbush schuyler.quackenbush@nyu.edu Lab Teaching Assistant TBD Description Syllabus MPATE-GE 2618: C Programming for Music

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

Starting to Program in C++ (Basics & I/O)

Starting to Program in C++ (Basics & I/O) Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and

More information

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut mith College CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 4 Hours! D. Thiebaut Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to

More information

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

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

More information

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

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

More information

Laboratory 1 Semester 1 11/12

Laboratory 1 Semester 1 11/12 CS2106 National University of Singapore School of Computing Laboratory 1 Semester 1 11/12 MATRICULATION NUMBER: In this lab exercise, you will get familiarize with some basic UNIX commands, editing and

More information

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018 CMPUT 201: Practical Programming Methodology Guohui Lin guohui@ualberta.ca Department of Computing Science University of Alberta September 2018 Lecture 1: Course Outline Agenda: Course calendar description

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

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

More information

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY ISA 563: Fundamentals of Systems Programming Announcements Homework 2 posted Homework 1 due in two weeks Typo on HW1 (definition of Fib. Sequence incorrect)

More information

Problem Set 1: Unix Commands 1

Problem Set 1: Unix Commands 1 Problem Set 1: Unix Commands 1 WARNING: IF YOU DO NOT FIND THIS PROBLEM SET TRIVIAL, I WOULD NOT RECOMMEND YOU TAKE THIS OFFERING OF 300 AS YOU DO NOT POSSESS THE REQUISITE BACKGROUND TO PASS THE COURSE.

More information

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

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

More information

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes Overview For this lab, you will use: one or more of the conditional statements explained below

More information

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input CpSc Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input Overview For this lab, you will use: one or more of the conditional statements explained below scanf() or fscanf() to read

More information

Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras

Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras Introduction to Operating Systems Prof. Chester Rebeiro Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 03 From Programs to Processes Hello. In

More information

CSE 124 Discussion (10/3) C/C++ Basics

CSE 124 Discussion (10/3) C/C++ Basics CSE 124 Discussion (10/3) C/C++ Basics Topics - main() function - Compiling with gcc/makefile - Primitives - Structs/Enums - Function calls/loops - C++ Classes/stdtl - Pointers/Arrays - Memory allocation/freeing

More information

C introduction: part 1

C introduction: part 1 What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

A brief introduction to C programming for Java programmers

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

More information

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function

More information

My malloc: mylloc and mhysa. Johan Montelius HT2016

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

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs. CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science Faculty of Computer Science Page 1 of 21 Final Exam Term: Fall 2018 (Sep4-Dec4) Student ID Information Last name: First name: Student ID #: CS.Dal.Ca userid: Course ID: CSCI 2132 Course Title: Instructor:

More information

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

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

More information

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

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

More information

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 3 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2017 ENCM 339 Fall 2017 Section 01

More information

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

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

More information

Recitation: C Review. TA s 20 Feb 2017

Recitation: C Review. TA s 20 Feb 2017 15-213 Recitation: C Review TA s 20 Feb 2017 Agenda Logistics Attack Lab Conclusion C Assessment C Programming Style C Exercise Cache Lab Overview Appendix: Valgrind Clang / LLVM Cache Structure Logistics

More information

Lectures 5-6: Introduction to C

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

More information

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Basic C Programming Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Announcements Exam 1 (20%): Feb. 27 (Tuesday) Tentative Proposal Deadline:

More information

CSSE 332 Standard Library, Storage classes, and Make

CSSE 332 Standard Library, Storage classes, and Make CSSE 332 Standard Library, Storage classes, and Make 1 Provides a simple and efficient buffered I/O interface from man stdio Prototypes standard I/O functions (Mostly) system-independent (e.g.

More information

Topic 6: A Quick Intro To C

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

More information

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

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

More information

CSC209 Review. Yeah! We made it!

CSC209 Review. Yeah! We made it! CSC209 Review Yeah! We made it! 1 CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files 2 ... and C programming... C basic syntax functions

More information

Processes. Johan Montelius KTH

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

More information

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 3 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2016 ENCM 339 Fall 2016 Slide Set 3 slide 2/46

More information

Programming in C week 1 meeting Tiina Niklander

Programming in C week 1 meeting Tiina Niklander Programming in C week 1 meeting 2.9.2015 Tiina Niklander Faculty of Science Department of Computer Science 3.9.2015 1 Course structure Based on C programming course in Aalto, but with some exercises created

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 C Strings, Arrays, & Malloc 2007-06-27 Scott Beamer, Instructor Sun announces new supercomputer: Sun Constellation CS61C L3 C Pointers

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

CS 300 Leftovers. CS460 Pacific University 1

CS 300 Leftovers. CS460 Pacific University 1 CS 300 Leftovers Pacific University 1 argc/argv The C Programming Language section 5.10, page 114 int main(int argc, char** argv) argc - number of entries in argv argv - array of character pointers containing

More information

A process. the stack

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

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430 Week 2 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430 1 Why is the Shell Important? Shells provide us with a way to interact with the core system Executes programs on

More information

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the

More information

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,

More information

Warm-up sheet: Programming in C

Warm-up sheet: Programming in C Warm-up sheet: Programming in C Programming for Embedded Systems Uppsala University January 20, 2015 Introduction Here are some basic exercises in the programming language C. Hopefully you already have

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

Creating a Shell or Command Interperter Program CSCI411 Lab

Creating a Shell or Command Interperter Program CSCI411 Lab Creating a Shell or Command Interperter Program CSCI411 Lab Adapted from Linux Kernel Projects by Gary Nutt and Operating Systems by Tannenbaum Exercise Goal: You will learn how to write a LINUX shell

More information

CSci 4061 Introduction to Operating Systems. IPC: Basics, Pipes

CSci 4061 Introduction to Operating Systems. IPC: Basics, Pipes CSci 4061 Introduction to Operating Systems IPC: Basics, Pipes Today Directory wrap-up Communication/IPC Test in one week Communication Abstraction: conduit for data exchange between two or more processes

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites: C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should

More information

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/16 1-dimensional Arrays Arrays can be statically declared in C, such as: int A [100]; The space for this

More information

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

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

More information

Today s Learning Objectives

Today s Learning Objectives Today s Learning Objectives 15-123 Systems Skills in C and Unix We will Review ints and modular arithmetic Learn basic Data types and Formats How Conditionals and loops work How Arrays are defined, accessed,

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX

More information

Getting Started. Project 1

Getting Started. Project 1 Getting Started Project 1 Project 1 Implement a shell interface that behaves similarly to a stripped down bash shell Due in 3 weeks September 21, 2015, 11:59:59pm Specification, grading sheet, and test

More information

Programming in C First meeting

Programming in C First meeting Programming in C First meeting 8.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 1 Course structure Weekly exercise deadline on Wednesday, lectures

More information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

C & Data Structures syllabus

C & Data Structures syllabus syllabus Overview: C language which is considered the mother of all languages, is and will be the most sought after programming language for any beginner to jump start his career in software development.

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

SWEN-250 Personal SE. Introduction to C

SWEN-250 Personal SE. Introduction to C SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the

More information

The C standard library

The C standard library C introduction The C standard library The C standard library 1 / 12 Contents Do not reinvent the wheel Useful headers Man page The C standard library 2 / 12 The Hitchhiker s Guide to the standard library

More information

IO = Input & Output 2

IO = Input & Output 2 Input & Output 1 IO = Input & Output 2 Idioms 3 Input and output in C are simple, in theory, because everything is handled by function calls, and you just have to look up the documentation of each function

More information

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam July 24, Name UW ID# Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information