computing science (cmput)...

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

Upload: others

Post on 03-Aug-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

Computing Science (CMPUT) 201Practical Programming Methodology

Paul Lu

Department of Computing ScienceUniversity of Alberta

[email protected]

Original material Copyright 2005–2007.

Some material from other instructors (e.g., Piotr Rudnicki) and sources.

Fall 2007

Page 2: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

Outline

Part I

Introduction

1 Key Points

2 Preparing for Labs

3 Overview

Page 3: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

Key Points

Keep in mind:

1 The course has an emphasis on C (not C++) underUnix.

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.

Page 4: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

Labs and Accounts

Labs start next week, September 10. NEW: There arelab exercises worth marks!Make sure that:

1 Before your lab, get your Unix accounts from Lab Adminand log in.http://ugweb.cs.ualberta.ca/accounts.html

Bring your ONE cardRead 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

Page 5: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

Goals of CMPUT 201

Goals:1 Teach the C programming language and model

syntax, memory, debugging, execution2 Teach the Unix programming model

standard in-out-error, pipes, basic API3 Teach some, practical aspects of programming

methodologycommon modularization techniques, value of simplicity,assertions, source code version control

Non-Goals:1 We assume knowledge of abstraction and

object-oriented design2 We assume you know Java

Page 6: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

How to succeed in CMPUT 201

1 Be fearless in “just trying it out”. It is hard to do anypermanent damage, if you use backups and versioncontrol.

Write small programs to test out concepts2 Learn to find the answers for yourself.

Your textbooks are excellent resourcesman pages are your friendGoogle your compiler error messagesthe Web knows (almost) all

3 Learn how to use the debugger.

Page 7: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

How to fail/drown in CMPUT 201

NOTE: The following points are intended to be ironic.

1 Continue to do things (i.e., write and debug) programsjust as you have always done.

2 Wait more than a year between taking CMPUT 115 toCMPUT 201.

3 Do not learn how to use the debugger.4 Do not take advantage of labs to ask questions of your

TAs5 Take 201 because “I am interested in learning a bit

more about how programming is done”. In fact, 201 isintended to help you master programming in C underUnix.201 is about “doing art” and not “art appreciation”.

Page 8: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Key Points

Preparing forLabs

Overview

Major Themes in CMPUT 201

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 anail."

2 Clear and simple should be preferred over clever andcomplex.

3 The difference between spending 10 hours vs. 100hours on an assignment will come down to “bestpractices”.

debugger, makefiles, assertions, “throw away” testprograms, incremental testing, automating repetitivetasksstart assignments on-timeTry to understand what you are doing, instead of justgetting something to work.

Page 9: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Outline

Part II

First Examples

4 Vertical StripRunning, CompilingFind Double WordMakefilesCompiler Warnings

5 Other Examplespopen: Child ProcessesBuffer File Contents

Page 10: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Vertical Strips

It would take years to develop a broad knowledge ofUnix and CVertical strips are examples that cut deeply throughmany different layers of abstraction, but in a shallowway at each layerFill out the details by consulting references and throughexperience

We depend on you to read, try, do, and ask your way toa mastery of the material.

Page 11: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

A Vertical Strip Example: Running Programs

paullu@ug30:~/C201>wget http://www.cs.ualberta.ca/~paullu/C201/sketchpad...snip...paullu@ug30:~/C201>wget http://www.cs.ualberta.ca/~paullu/C201/example.a1.sketchpad...snip...paullu@ug30:~/C201>ls -lttotal 96-rw------- 1 paullu prof 92418 Sep 6 15:42 sketchpad-rw------- 1 paullu prof 170 Sep 6 15:41 example.a1.sketchpadpaullu@ug30:~/C201>chmod +x ./sketchpadpaullu@ug30:~/C201>ls -lttotal 96-rwx------ 1 paullu prof 92418 Sep 6 15:42 sketchpad*-rw------- 1 paullu prof 170 Sep 6 15:41 example.a1.sketchpadpaullu@ug30:~/C201>./sketchpad < example.a1.sketchpad

NOTE: For all the notes, file sizes and timestamps maydiffer from reality.

1 The Unix shell (e.g., bash, tcsh) prompts the user forcommands to execute with paullu@ug30

2 wget, ls, and sketchpad are all programs executedfrom the command line of the shell.Unix is often used via the command-line interface

Page 12: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

man pages

Manual (man) pages are the traditional, on-linedocuments for Unix.

man wget: details for a specific programman -k http: does a (lame) search using http askeywordman man: details how to use man

Often, Unix commands have esoteric command-lineoptions. For example, ls -lt.

ls: the “list directory contents” program-l: long listing format-t: sort by the timestamp

Page 13: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Compiling Programs

paullu@ug30:~/C201>ls -lttotal 100-rw------- 1 paullu prof 2072 Sep 7 00:17 finddw.cpaullu@ug30:~/C201>gcc -Wall -ansi finddw.c -o finddw...snip (some compiler warnings)...paullu@ug30:~/C201>ls -lttotal 116-rwx------ 1 paullu prof 14391 Sep 7 00:19 finddw*-rw------- 1 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 gcc3 -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

Page 14: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Running Find Double Word

paullu@ug30:~/C201>cat finddw.testSometimes, it is is easy towrite the same word twicetwice and not make a spelling mistake.

paullu@ug30:~/C201>./finddw finddw.testIn file finddw.test, repeated word: is isContext: easy to

Re-run program after fixing!!!In file finddw.test, repeated word: twice twiceContext: and not make a spelling mistake.

Re-run program after fixing!!!

paullu@ug30:~/C201>cat finddw.okThis file is fine.There is nothing to worry about.paullu@ug30:~/C201>./finddw finddw.okpaullu@ug30:~/C201>

cat is a program to send the contents of a file to theterminalfinddw knows which file to use from the command-lineargument

Page 15: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word

paullu@ug30:~/C201>cat 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 variablesfunction prototypes

Page 16: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word (2)

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)

The main() function is where the program starts executing. The Unix shellfinds the executable and starts running it at function main().main() is a function, not a method. But, it has similar syntax in its functiondefinition compared to Java.

Page 17: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word (3)

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

Page 18: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word (4)

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 toJava

C input/output is by the Standard I/O (stdio) library (e.g., printf())

Page 19: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word (5)

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 thesemantics, not the syntax

90% of the time, clear code that follows standard conventions is preferredover clever code

C input is by the Standard I/O (stdio) library (e.g., fscanf())

Page 20: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Find Double Word (6)

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 JavaC strings are handled using a family of functions (e.g., strncmp(),strncpy())

Page 21: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Makefiles

paullu@ug30:~/C201>cat Makefile# A simple makefile

finddw: finddw.cgcc -Wall -ansi finddw.c -o finddw

paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddw

1 By default, the program make looks for Makefile ormakefile (which are text files).

2 Makefiles are examples of declarative programs: Youtell the system what you want, more than how toachieve it. In truth, it is a hybrid of declarative andimperative.

3 First Common Pitfall: The white space in front of gcc-Wall ... is actually an invisible tab.

Page 22: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Makefiles (2)

paullu@ug30:~/C201>cat Makefile# A simple makefile

finddw: finddw.cgcc -Wall -ansi finddw.c -o finddw

paullu@ug30:~/C201>makegcc -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 finddw1 Defines an action (aka construction-commands).2 Actions are anything that you can do from the Unix

command line.

Page 23: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model

paullu@ug30:~/C201>cat Makefile# A simple makefile

finddw: finddw.cgcc -Wall -ansi finddw.c -o finddw

paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddw

1 In this example, make and make finddw have thesame effect.

2 When you execute make1 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.

Page 24: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (2)

paullu@ug30:~/C201>cat Makefile# A simple makefile

finddw: finddw.cgcc -Wall -ansi finddw.c -o finddw

paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddw

1 If the target is less recent than the dependencies, or ifthe target does not exist, then make invokes the targetsfor 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 refactoringcode. Solution: Be careful. And, have a make cleantarget, as discussed below.

Page 25: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (3)

paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddwpaullu@ug30:~/C201>makemake: ‘finddw’ is up to date.paullu@ug30:~/C201>touch finddw.cpaullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddw

paullu@ug30:~/C201>which whichwhich: shell built-in command.paullu@ug30:~/C201>which touch/usr/bin/touch

1 touch is a Unix command that “updates” thetimestamp of a file to, for example, simulate editing afile. The contents of the file does not change.

2 Notice how make’s declarative execution model onlylooks at timestamps, and does not look at the contentsof a file.

3 which is a Shell command to tell you where (or which)an executable is located

Page 26: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (4)

paullu@ug30:~/C201>cat Makefile.v2finddw: finddw.c

gcc -Wall -ansi finddw.c -o finddw

clean:-rm *.o finddw

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 actionsand/or targets and dependencies can be automated via aMakefile.Target clean is a common target (and required in yourassignments). Note that you should never have a file withthe name clean.

Page 27: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (5)

paullu@ug30:~/C201>cat Makefile.v2finddw: finddw.c

gcc -Wall -ansi finddw.c -o finddw

clean:-rm *.o finddw

tar: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 (morelater).For example, executable finddw is created from .cfiles.The - in front of rm says, “If the action should fail in anyway, continue with the next action”

Page 28: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (6)

paullu@ug30:~/C201>make -f Makefile.v2 cleanrm *.o finddwrm: cannot remove ‘*.o’: No such file or directorymake: [clean] Error 1 (ignored)paullu@ug30:~/C201>make -f Makefile.v2gcc -Wall -ansi finddw.c -o finddwpaullu@ug30:~/C201>touch READMEpaullu@ug30:~/C201>make -f Makefile.v2 tartar cvf submit.tar finddw.c Makefile READMEfinddw.cMakefileREADME

1 Target tar automates the error-prone command tocreate a tape archive (tar) file.

The cvf command-line options say: create a new tarfile, be verbose when doing so, and use the filenamethat follows immediately after the cvf (i.e.,submit.tar).After the cvf submit.tar is the list of files to put intothe tar file.

2 Common Pitfall: It is a big mistake to do somethinglike: tar cvf finddw.c Makefile README.

Page 29: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (7)

paullu@ug30:~/C201>cat Makefile.v3finddw: finddw.o

gcc -Wall -ansi finddw.o -o finddw

finddw.o: finddw.cgcc -Wall -ansi -c finddw.c

clean:-rm *.o finddw

tar:tar cvf submit.tar finddw.c Makefile README

paullu@ug30:~/C201>make -f Makefile.v3 finddw.ogcc -Wall -ansi -c finddw.cpaullu@ug30:~/C201>ls -lt *.o-rw------- 1 paullu prof 2020 Sep 11 18:09 finddw.opaullu@ug30:~/C201>make -f Makefile.v3 finddwgcc -Wall -ansi finddw.o -o finddwpaullu@ug30:~/C201>ls -lt finddw*-rwx------ 1 paullu prof 14391 Sep 11 18:09 finddw*-rw------- 1 paullu prof 2020 Sep 11 18:09 finddw.o-rw------- 1 paullu prof 2072 Sep 11 16:35 finddw.c-rw------- 1 paullu prof 52 Sep 9 01:15 finddw.ok-rw------- 1 paullu prof 93 Sep 9 01:08 finddw.testpaullu@ug30:~/C201>make -f Makefile.v3 cleanrm *.o finddwpaullu@ug30:~/C201>make -f Makefile.v3gcc -Wall -ansi -c finddw.cgcc -Wall -ansi finddw.o -o finddwpaullu@ug30:~/C201>

1 The gcc -Wall -ansi -c illustrates separatecompilation in C.

Page 30: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Make Execution Model (8)

paullu@ug30:~/C201>cat Makefile.v3finddw: finddw.o

gcc -Wall -ansi finddw.o -o finddw

finddw.o: finddw.cgcc -Wall -ansi -c finddw.c

clean:-rm *.o finddw

tar:tar cvf submit.tar finddw.c Makefile README

paullu@ug30:~/C201>make -f Makefile.v3 finddw.ogcc -Wall -ansi -c finddw.cpaullu@ug30:~/C201>ls -lt *.o-rw------- 1 paullu prof 2020 Sep 11 18:09 finddw.opaullu@ug30:~/C201>make -f Makefile.v3 finddwgcc -Wall -ansi finddw.o -o finddw...snip...

The gcc -Wall -ansi -c illustrates separatecompilation in C.

Page 31: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Compiler Warnings

paullu@ug30:~/C201>head -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>makegcc -Wall -ansi finddw.c -o finddwfirst.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 generatecompiler warnings.

2 Warnings are not the same, fatal things as errors. But,good programming style and methodology requires thatwarnings be fixed.

Page 32: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Compiler Warnings (2)

paullu@ug30:~/C201>head -2 finddw.c#include <stdio.h>#include <string.h> /* For strncmp(), etc. */paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddwfirst.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) showsthat I need #include <stdlib.h>.

At the end of man exit, there is a SEE ALSO sectionthat pointed me to exit(3), which is why we need todo man 3 exit.

2 The man page for isalpha() (i.e., man isalpha)shows that I need #include <ctype.h>.

Page 33: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Compiler Warnings (3)

paullu@ug30:~/C201>head -5 finddw.c#include <stdio.h>#include <string.h> /* For strncmp(), etc. */#include <stdlib.h> /* For exit(), etc. */#include <ctype.h> /* For isalpha(), etc. */

paullu@ug30:~/C201>makegcc -Wall -ansi finddw.c -o finddw

1 The warnings have now been fixed.2 Remember, your main tools for this are:

Man pagesGoogleYour textbooksYour TAs, instructor, and fellow students.

Page 34: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

popen

paullu@ug30:~/C201>gcc -Wall -ansi testpopen.cpaullu@ug30:~/C201>./a.outhellopaullu@ug30:~/C201>cat testpopen.c#include <stdio.h>#include <stdlib.h> /* For exit() */

extern FILE *popen(const char *command, const char *type);extern 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 */

Page 35: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

popen (2)

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 createa helper, child process to perform a function. There is acorresponding pclose function.

2 Unix is a multiprocessing operating system: differentprocesses (i.e., programs being executed) can runconcurrently (i.e., at the same time).

3 This is a powerful abstraction and modularizationtechnique, especially since the programs/processescan be written in any language.

Page 36: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

popen (3)

fprintf( fppo, "greetings\n" );fprintf( fppo, "hello\n" );fprintf( fppo, "good bye\n" );pclose( fppo );

return( 0 );} /* main */

1 popen returns a FILE * (aka file pointer). This is thesame file pointer seen in the finddw example for openfiles. You can fprintf(), fscanf(), etc.

2 In Unix, many different “objects”, interfaces, andmechanisms (i.e., a specific abstraction by which toaccomplish a task) look like files. Sometimes, thesimilarity is incomplete; you use pclose() instead offclose() here.

3 This is a powerful abstraction and modularizationtechnique, especially since the programs/processescan be written in any language.

Page 37: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

popen (4)

Also1 The same ability to combine or pipeline processes can

be done from the command line of the shell. Thismeans one can fearlessly try pipelines beforeincorporating them in one’s program.paullu@ug30:~/C201>cat input.file | grep hellohellopaullu@ug30:~/C201>./a.outhellopaullu@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 isalso the system() library function for running childprocesses.

system( "cat -n finddw.c | grep \"^ *63\"" );

3 But, what are the disadvantages of concurrentprocesses and the “everything is a file” designphilosophy?

Page 38: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory and Buffer 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 forheterogeneous, aggregate data structures.

2 The closest thing in Java is a class. Structures are likeclasses with only public data members.

Structures and classes are templates and must beinstantiated (aka allocated).But, structures do not have associated methods as partof the structure itself. Abstract data types (ADTs) arecreated using structures plus other techniques.

Page 39: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Structures

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” withstruct 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 ofobjects).

Page 40: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (2)

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 */

Page 41: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (3)

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. Thereare no Java-like constructors.

2 Initializing strings is particularly good, defensiveprogramming methodology. Highly recommended bestpractice.

3 Once you understand the memory model of C andstrings, memset() is a quick, easy, and effective way toinitialize things.

4 The sizeof() operator is also useful for staticallyallocated data structures, as we see here.

Page 42: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (4)

/* currentLine is passed-by-reference/pointer */bufferFile( fp, theLines, &currentLine, MAX_LINES );

The default for parameter passing is pass-by-value (likeJava). But, what value?

1 Arrays and strings (which are arrays) always pass thevalue of the pointer. They are implicitlypass-by-reference (aka pass-by-pointer).Pass-by-reference is an important way to get data outof a function (aka persistence).

2 For other (smaller) data types, the value of thevariable is passed. In this call site example, onlyMAX_LINES is pass-by-value.

3 But, the programmer can explicitly choose and usepass-by-reference. The parameter &currentLine isalso an example of pass-by-reference. The functionitself has to be expecting pointers, as necessary.

Page 43: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (5)

/* 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 amethod affect the actual object. This is likepass-by-reference (of objects) in the C world.

3 Changes to the reference do not affect the originalreference since the reference itself is pass-by-value.

4 So, the way C treats arrays (and strings) is analogousto the way Java treats object references. But, for othertypes, C gives you a choice.

Page 44: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (6)

else{

/* currentLine is passed-by-reference/pointer */bufferFile( fp, theLines, &currentLine, MAX_LINES );fclose( fp );

}

1 fp is a pointer, despite not having an &, because it isalready 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[], anarray. 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 apointer? No. Why not?

Page 45: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (7)

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

*currentLinePtr);}

} /* bufferFile */

Page 46: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (8)

void bufferFile( FILE * fp, struct aLine * theLines, int * currentLinePtr,int maxLines )

{...snip...} /* bufferFile */

1 If a parameter is supposed to be a pointer, it alwayshas the form with * or [].

fp, theLines, currentLinePtrNote that [] is just another way to say *, which is whychar * argv[] and char ** argv are the same!

Page 47: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (9)

/* 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->).

Page 48: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (10)

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 andgreat 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>makegcc -Wall -ansi bufferfile.c -o bufferfilebufferfile.c: In function ‘bufferFile’:bufferfile.c:53: warning: comparison between pointer and integer

3 But, it was only a warning. The executable was stillcreated!

Page 49: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (11)

/* 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 inmain()

2 theLines[ *currentLinePtr ]: The arraytheLines in main(), at index currentLine inmain()

Page 50: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (12)

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 ofcurrentLine in main(). The dereferencing happensbefore the increment.

Page 51: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (13)

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;

}

/* Check for matrix definitions */memset( firstWord, 0, MAX_BUF ); /* Initialize. Defensive. */rval = sscanf( theLines[ currentLine ].line, "%s", firstWord );if( rval != 1 ){

#if 0printf( "Error in sscanf\n" );

#endifreturn;

}if( strncmp( firstWord, "Matrix", 6 ) ) == 0 ){

theLines[ currentLine].type = 1;}

} /* classifyLine */

Page 52: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (14)

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, defensiveprogramming and a best practice.

2 theLines[ currentLine ].line[0] == ’#’Refers to the first character of field line of thestructure at index currentLine, in the arraytheLines 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

Page 53: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (15)

/* Check for matrix definitions */memset( firstWord, 0, MAX_BUF ); /* Initialize. Defensive. */rval = sscanf( theLines[ currentLine ].line, "%s", firstWord );if( rval != 1 ){

#if 0printf( "Error in sscanf\n" );

#endifreturn;

}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 infscanf() gets its input from a file, via a file pointer

3 We use sscanf() to automatically handle white spaceissues

Page 54: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (16)

/* Check for matrix definitions */memset( firstWord, 0, MAX_BUF ); /* Initialize. Defensive. */rval = sscanf( theLines[ currentLine ].line, "%s", firstWord );if( rval != 1 ){

#if 0printf( "Error in sscanf\n" );

#endifreturn;

}if( strncmp( firstWord, "Matrix", 6 ) ) == 0 ){

theLines[ currentLine].type = 1;}

1 #if 0 and #endif are examples of conditionalcompilation. Here, it means do not include theprintf() line. Use this technique for your owndebugging output; see assignment description.

2 Frankly, hard-coding the 6 for the strncmp() is not thebest idea. It is OK and used for simplicity here.

Page 55: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Vertical StripRunning, Compiling

Find Double Word

Makefiles

Compiler Warnings

OtherExamplespopen: ChildProcesses

Buffer File Contents

Read a File Into Memory (17)

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 acomment.

Page 56: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Outline

Part III

The C Language6 The C Language (1)

Thinking in CMemory ModelArrays and Strings in Memory

7 The C Language (2)Linked ListsMultidimensional Arrays

8 The C Language (3)Storage and ScopeFunction PointersInitialization

Page 57: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Thinking in C vs. Java

There are a number of differences that require a newway of thinking.C is sometimes known as a “portable, high-levelassembly language” and is often used to writeoperating systems, database management systems,graphics systems because C allows you to have:

1 power: manage and manipulate memory down to asingle bit, or access I/O devices

2 performance: have a simple mapping from C constructto execution model

3 understandability: does not have (many) hiddenoverheads and side effects

4 functionality: many libraries and good support on Unix

Page 58: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Thinking in C vs. Java (2)

But, with power comes more responsibility for theprogrammer:

1 C does not have automatic initialization/finalization viaconstructors/destructors

2 C does not have automatic array bounds checking3 C does not have garbage collection4 C will let you bypass type checking, both explicitly and

implicitly5 C will let you modify any part of the user’s address

space

The programmer must learn the model, the “bestpractices”, and the standard toolset (e.g., debuggers)C can be used for any kind of programming. But, it isnot the best choice for all kinds of applications.We all need to know C because of all the C code “outthere”, including Linux, compilers (e.g., gcc), etc.

Page 59: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Thinking in C vs. Java (3)

1 Instead of Java’s objects, think of C’s structures andabstract data types (ADT)

2 Instead of Java’s class methods, think of C’s functionswith similar parameter types (e.g., FILE * forfprintf(), fscanf())

3 Instead of Java’s method overloading, think of C’sfunctions with different but similar names (e.g.,scanf(), fscanf(), sscanf())

4 Instead of Java’s string class, think of C’s arrays ofmemory and buffers used to hold characters and otherdata

5 Instead of Java’s garbage collection, think of C’sfree(), fclose(), pclose(), etc.

Page 60: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Thinking in C vs. Java (4)

6 Instead of Java’s object references, think of C’s pointersto anything

7 Instead of Java’s exceptions, think of a C function’sreturn value and the global variable errno

8 Instead of Java’s import feature for packages, think ofC’s header files (i.e., #include) and linking to libraries

9 Instead of Java’s virtual machine, think of C’s executionmodel and address space organization

10 Instead of Java’s libraries, think of C’s libraries and Unixsystem calls

Page 61: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Thinking in C vs. Java (5)

11 Instead of Java’s boolean FALSE and TRUE, think of C’sinterpretation of zero and non-zero values. (NOTE: C99does have a bool type.)

12 Instead of Java’s new and garbage collection, think ofC’s library functions malloc(), calloc(), andfree()

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 designpattern) in C. But, it is often non-obvious or much morecomplicated.

Page 62: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space

A process is a program being executed.The von Neumann model includes the notion that codeand data are stored in a common memory. We call thatan 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 bythe 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, functionparameters, and tracking nested functions calls andrecursion

Page 63: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space (2)

Kernel Space

Data

Heap

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

“Stack” segment: Localvariables, function parameters,support for function calls

Grows from high to lowmemory

“Heap” segment: Dynamicmemory, malloc()

Grows from low to highmemory

Global “data” segment: Globalvariables and constantsProgram “text” segment: Code

Page 64: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space (3)

We also distinguish between:1 User space: parts of memory that can be accessed by

normal programs1 The user’s code and data2 Library code and data

2 Kernel or OS space: parts of memory that can only beaccessed by the operating system

A “segmentation fault” refers to an inappropriate accessto a part of memory, usually due to a wrong pointer oroverflowing a buffer.And, we distinguish between:

1 Physical memory: RAM chips2 Logical memory: An illusion of memory provided by the

OS (a big topic in CMPUT 379)

Page 65: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space (4)

Kernel Space

Data

Heap

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

NOTE: Numbers may vary.

paullu@ug30:~/C201>cat t1.c#include <stdio.h>

char Buffer[ 8 ];int GlobalI;

int main( int argc, char * argv[] ){

int localI;

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.cpaullu@ug30:~/C201>./a.outBuffer = 0x8049680 / 134518400GlobalI = 0x8049688 / 134518408localI = 0xbffffa94 / 3221224084&(Buffer[ 7 ]) = 0x8049687 / 134518407

Page 66: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space (5)

Kernel Space

Data

Heap

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

#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.outmain(localI) = 0xbffffa94 / 3221224084sub (localI) = 0xbffffa84 / 3221224068GlobalI = 0x80496cc / 134518476main() = 0x80483a4 / 134513572sub() = 0x8048384 / 134513540

Page 67: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

A Process’s Address Space (6)

Kernel Space

Data

Heap

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

paullu@ug30:~/C201>./a.out&str = 0xbffffa94 / 3221224084str = 0xbffffaf4 / 3221224180str = 0x8049750 / 134518608str2 = 0x80485c9 / 134514121

&str = 0xbffffa80 / 3221224064str = 0x8049750 / 134518608

#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",&str, (int)&str );

printf( " str = %p / %u\n",str, (int)str );

str = malloc( 16 );printf( " str = %p / %u\n",

str, (int)str );printf( " str2 = %p / %u\n",

str2, (int)str2 );sub( str );return( 0 );

} /* main */

Page 68: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory

str

Data

Heap

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

Kernel Space

0xbffffa94 0xbffffaf4 (junk!)

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.cpaullu@ug30:~/C201>./a.out&str = 0xbffffa94 / 3221224084str = 0xbffffaf4 / 3221224180str = 0x8049798 / 134518680str2 = 0x80485c4 / 134514116

Page 69: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory (2)

0x08049798

High Memory: 4 GB

Low Memory: 00x00000000

0xffffffff

Kernel Space

Text

Stack

Kernel Space

0xbffffa94str

Heap

Data0x080485c4 Hello\0

str20xbffffa40 0x080485c4

0x08049798

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.cpaullu@ug30:~/C201>./a.out&str = 0xbffffa94 / 3221224084str = 0xbffffaf4 / 3221224180str = 0x8049798 / 134518680str2 = 0x80485c4 / 134514116

Page 70: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory (3)

0x080497a7

0xbffffa94str

str20xbffffa40 0x080485c4

0x08049798

0x080485c4

0x080485c5

0x080485c6

0x080485c7

0x080485c8

0x080485c9

H

o

e

ll

\0

0x08049798

0x08049799

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.cpaullu@ug30:~/C201>./a.out&str = 0xbffffa94 / 3221224084str = 0xbffffaf4 / 3221224180str = 0x8049798 / 134518680str2 = 0x80485c4 / 134514116

Page 71: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory (4)

0x080497a7

0xbffffa94str

str20xbffffa40 0x080485c4

0x08049798

0x080485c4

0x080485c5

0x080485c6

0x080485c7

0x080485c8

0x080485c9

H

o

e

ll

\0

0x08049798

0x08049799

&( str[ 0 ] ) is 0x08049798&( str[ 1 ] ) is 0x08049799&( str[ 2 ] ) is 0x0804979a&( str[ 3 ] ) is 0x0804979b&( str[ 4 ] ) is 0x0804979c&( str[ 5 ] ) is 0x0804979d&( str[ 6 ] ) is 0x0804979e&( str[ 7 ] ) is 0x0804979f&( str[ 8 ] ) is 0x080497a0...&( str[ 15 ] ) is 0x080497a7&( str[ 16 ] ) is 0x080497a8 (overflow!)

&( str2[ 0 ] ) is 0x080485c4, str2[ 0 ] == ’H’&( str2[ 1 ] ) is 0x080485c5, str2[ 1 ] == ’e’&( str2[ 2 ] ) is 0x080485c6, str2[ 2 ] == ’l’&( str2[ 3 ] ) is 0x080485c7, str2[ 3 ] == ’l’&( str2[ 4 ] ) is 0x080485c8, str2[ 4 ] == ’o’&( str2[ 5 ] ) is 0x080485c9, str2[ 5 ] == ’\0’

Page 72: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory (5)

0xbffffa90

0xbffffa80

0xbffffa84

0xbffffa88

0xbffffa8c

paullu@ug30:~/C201>cat t5.c#include <stdio.h>

int main( int argc, char * argv[] ){

int m[ 4 ];

printf( "&( m[ 0 ] ) = %p\n", &( m[ 0 ] ) );printf( "&( m[ 1 ] ) = %p\n", &( m[ 1 ] ) );printf( "&( m[ 2 ] ) = %p\n", &( m[ 2 ] ) );printf( "&( m[ 3 ] ) = %p\n", &( m[ 3 ] ) );/* No valid index 4, but C doesn’t care */printf( "&( m[ 4 ] ) = %p\n", &( m[ 4 ] ) );return( 0 );

} /* main */paullu@ug30:~/C201>gcc -Wall -ansi t5.cpaullu@ug30:~/C201>./a.out&( m[ 0 ] ) = 0xbffffa80&( m[ 1 ] ) = 0xbffffa84&( m[ 2 ] ) = 0xbffffa88&( m[ 3 ] ) = 0xbffffa8c&( m[ 4 ] ) = 0xbffffa90

&( m[ 2 ] ) = 0xbffffa80 + ( 2 * sizeof(int) )

Be careful of big vs. little endianissues (see CMPUT 229).

Page 73: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Arrays and Strings in Memory (6)

There is a “clear”mapping of indexingto assembly code.

paullu@ug30:~/C201>cat t6.c#include <stdio.h>

int M[ 4 ];

int main( int argc, char * argv[] ){

int i;

M[ 2 ] = 1;M[ i ] = 2;return( 0 );

} /* main */

paullu@ug30:~/C201>gcc -S -Wall -ansi t6.cpaullu@ug30:~/C201>cat t6.s

.file "t6.c"

.text.globl main

.type main, @functionmain:

pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espmovl $1, M+8 /* M[ 2 ] = 1 */movl -4(%ebp), %eax /* Load i */movl $2, M(,%eax,4) /* M[ i ] = 2 */movl $0, %eaxleaveret.size main, .-main.comm M,16,4.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 74: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked Lists

3

payload next payload nextpayload next

NULL1 2

A linked list uses dynamic memory allocation andpointers to implement abstract, sequential arrays thatcan be of arbitrary size.Although C has pointers and Java has objectreferences, the basic ideas behind linked lists are thesame.The main issues are (see King, page 370):

1 How to declare the basic structure?2 How to allocate a node?3 How to use a node?4 How to insert a node into the list?5 How to find a node?6 How to delete a node?

Page 75: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

How to declare the basic structure?

payload next

1

Typically, one uses astruct

You can have a structNode * inside thedeclaration of the structureitselfThe payload (or contents)can be anything, includingother structures, arrays,other pointers (careful!), etc.

#include <stdio.h>#include <stdlib.h>#include <assert.h>

struct Node{

int payload;struct Node * next;

};

struct Node * HeadList = NULL;

int main( int argc, char * argv[] ){

struct Node * newNode;

newNode = malloc( sizeof( struct Node ) );assert( newNode != NULL );

newNode->payload = 1;

/* Insert at head of list */newNode->next = HeadList;HeadList = newNode;

return( 0 );} /* main */

Page 76: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

How to allocate/use a node?

HeadList payload next

NULL1

When using malloc(), becareful to use the rightexpression.

sizeof( struct Node )

== 8

sizeof( struct * Node )

== 4

The arrow operator (->)newNode->payload = 1 isthe same as(*newNode).payload = 1

You must use malloc() fordynamic allocation

#include <stdio.h>#include <stdlib.h>#include <assert.h>

struct Node{

int payload;struct Node * next;

};

struct Node * HeadList = NULL;

int main( int argc, char * argv[] ){

struct Node * newNode;

newNode = malloc( sizeof( struct Node ) );assert( newNode != NULL );

newNode->payload = 1;

/* Insert at head of list */newNode->next = HeadList;HeadList = newNode;

return( 0 );} /* main */

Page 77: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

How to find a node?

currNode

payload next payload nextpayload next

NULL1 2 3

prevNode

Never dereference a pointerthat might be NULL.

while(currNode != NULL)

Either fix your control flow,or use an assertion.It is OK to assign a NULL.

int main( int argc, char * argv[] ){

struct Node * currNode, * prevNode;

/* Find */currNode = HeadList;prevNode = NULL;while( currNode != NULL ){

if( currNode->payload == 2 )break;

prevNode = currNode;currNode = currNode->next;

} /* while */

/* Delete */if( currNode != NULL ){

if( currNode == HeadList ){

HeadList = currNode->next;}else if( prevNode != NULL ){

prevNode->next = currNode->next;}free( currNode );

} /* if */

} /* main */

Page 78: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

How to delete a node?

currNode

payload next payload nextpayload next

NULL1 2 3

prevNode

Never dereference a pointerthat might be NULL.

if(currNode != NULL)

if(prevNode != NULL)

Deleting the first node of alist is a special caseIt is OK to assign a NULL.

int main( int argc, char * argv[] ){

struct Node * currNode, * prevNode;

/* Find */currNode = HeadList;prevNode = NULL;while( currNode != NULL ){

if( currNode->payload == 2 )break;

prevNode = currNode;currNode = currNode->next;

} /* while */

/* Delete */if( currNode != NULL ){

if( currNode == HeadList ){

HeadList = currNode->next;}else if( prevNode != NULL ){

prevNode->next = currNode->next;}free( currNode );

} /* if */

} /* main */

Page 79: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Miscellaneous

It is a good idiom and best practice to immediatelyinitialize a new node.

newNode = malloc( sizeof( struct Node ) );assert( newNode != NULL );memset( newNode, 0, sizeof( struct Node ) );

ornewNode = calloc( 1, sizeof( struct Node ) );assert( newNode != NULL );

See the King textbook for more information and adifferent perspective.Was the check if( prevNode != NULL ) actuallynecessary?

Page 80: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Testing

The best programmers are also good debuggers andgood testers.Good testing is another example of paying “attention todetail”.

Imagine how silly it would be to build a car, check thatthe radio works, and then declare it ready for use.Imagine how silly it would be to build a car, drive it downthe alley–once, and then declare it ready for use.

In Real World programming projects (e.g., Mozilla,Firefox), a Nightly Build and testing is an expectedpractice. Seehttp://www.mozilla.org/developer/#builds

Testing can find bugs. But, testing cannot prove that aprogram is bug free. But, you must still test, test, test.

Page 81: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Testing (2)

Some testing should be done by someone who did notwrite the code.

Video game companies employ lots of testers, who arenot developers.You are allowed to (encouraged to!) post your testcases in the newsgroup. Post your tests, not your code.

The field of software engineering has a lot of ideas andtheories about testing.

1 White box vs. black box tests2 Unit vs. integration tests3 Coverage4 Pre-conditions and post-conditions5 Formal methods

Page 82: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Testing (3)

Some key, practical rules of thumb are:

1 Testing should be done often.

Testing is part of the programming process. Testing isNOT something done just before a deadline. (Anotherexample of “find problems early”.)Make it easy by creating (and updating) a make testtarget in your Makefile.Consider a make fulltest too.Use it just before submitting your assignment. Use it, ona fresh untar’ed copy of your code, after you submit.The “extreme programming” school argues that a good,automatic testing infrastructure can actually speed upsoftware development by giving the programmerconfidence about code changes.

Page 83: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Testing (4)

2 When you find a bug via testing, fix it, but also

Look for other places in the code for similar bugs.Add relevant assert()sAdd a new test case.Re-write the code if the bug was caused by bad style orbad design.

3 When you add a new feature or a new abstract datatype (ADT), make sure you add new tests as well.

4 Design tests for the “corner cases”. Be paranoid.Understand why things can go wrong.

Page 84: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Testing (5)

Let’s use the linked list as a case study:

1 Consider a function testLinkedList(). More detailsshortly.

2 Corner cases to unit test:1 Adding the first node to an empty list.2 Delete the first node, immediately.3 Try to delete a node, but linked list is empty.4 Add several nodes.5 Search for a node that exists.6 Search for a node that does not exist.7 Search for a node that exists and is at the head.8 Search for a node that exists and is at the tail.9 Delete a node. Repeat the search tests.

10 Delete all nodes, start with the head node.11 Delete all nodes, start with the tail node.12 Delete all nodes, start with the middle node.

Page 85: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Separate compilation

You can use separate compilation to help with testing.You can also use separate compilation to create ADTs.Separate compilation allows you modularize your codeinto different .c files.

1 The separate .c files can be compiled independently(and linked together).

2 A .c file can implement one ADT.3 Debugging and testing code can be factored into a

separate .c file.

Page 86: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Separate compilation (2)

Suppose you wanted to create a Linked List ADT.

1 First, use a header file to declare the data structures,functionality, interface, or behaviour.% cat linkedlist.h#ifndef _LINKEDLIST_H_#define _LINKEDLIST_H_

#define MAX_SOMETHING 128

struct Node{

int payload;struct Node * next;

};

extern struct Node * HeadList; /* Declaration */

extern void initializeLinkedList( struct Node * head );extern void addToList( struct Node * head, struct Node * node );extern void deleteFromListByKey( struct Node * head, int key );extern struct Node * searchListByKey( struct Node * head, int key );

#endif /* _LINKEDLIST_H_ */

Do NOT put code or variable definitions in the header file.

Page 87: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Separate compilation (3)

2 Second, use a source file (aka .c file) to definevariables and functions.% cat linkedlist.c#include "memwatch.h"#include "linkedlist.h"

struct Node * HeadList = NULL; /* Definition */

void initializeLinkedList( struct Node * head ){

...code here...} /* initializeLinkedList */

void addToList( struct Node * head, struct Node * node ){

...code here...} /* addToList */

void deleteFromListByKey( struct Node * head, int key );{

...code here...} /* deleteFromListByKey */

struct Node * searchListByKey( struct Node * head, int key );{

...code here...} /* searchListByKey */

Page 88: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Separate compilation (4)

3 Third, compile the source file into an object file (aka .ofile).% gcc -Wall -ansi -DMEMWATCH -DMW_STDIO -c linkedlist.c% ls *.olinkedlist.o

4 Fourth, link the object files together to createfull-fledged executables.% cat testlinkedlist.c#include "memwatch.h"#include "linkedlist.h"

void testLinkedList(){

...code here...} /* testLinkedList */

int main( int argc, char * argv[]){

testLinkedList();} /* main */% gcc -Wall -ansi -DMEMWATCH -DMW_STDIO -c testlinkedlist.c% gcc -Wall -ansi testlinkedlist.o linkedlist.o -o mytest

or% gcc -Wall -ansi main.o linkedlist.o -o myexecutable

Page 89: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Linked List: Separate compilation (4)

5 Fifth, automate everything with your Makefile.% cat Makefilemyexecutable: main.o linkedlist.o

gcc -Wall -ansi main.o linkedlist.o -o myexecutable

mytest: testlinkedlist.o linkedlist.ogcc -Wall -ansi testlinkedlist.o linkedlist.o -o mytest

linkedlist.o: linkedlist.c linkedlist.hgcc -Wall -ansi -DMEMWATCH -DMW_STDIO -c linkedlist.c

main.o: main.c linkedlist.hgcc -Wall -ansi -DMEMWATCH -DMW_STDIO -c main.c

testlinkedlist.o: testlinkedlist.c linkedlist.hgcc -Wall -ansi -DMEMWATCH -DMW_STDIO -c testlinkedlist.c

test:make myexecutable./myexecutable test.in.1./myexecutable test.in.2

testunit:make mytest./mytest

Of course, you can use variables and constants (e.g.,CFLAGS) in your Makefile

Page 90: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays

So far, none of the assignments in CMPUT 201 hasrequired the use of multidimensional arrays.Scientific, math-oriented programs can requiremultidimensional arrays.Non-math-oriented (aka integer) programs tend to usestructures, arrays of structures, and pointer-based datastructures.For Assignment #2, you do NOT need to usemultidimensional arrays. Consider an ADT approachinstead.Case 1: If the dimensions of the array are known atcompile-time (i.e., are static), then multidimensionalarrays are easy. (See King pg. 146)

Page 91: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (2)

#include <stdio.h>#define SIZE 2int main( int argc, char ** argv ){

int m[ SIZE ][ SIZE ], * mAlt, i, j;

/* Access like multidimensional array */for( i = 0; i < SIZE; i++ ){

printf( "%2d: ", i );for( j = 0; j < SIZE; j++ ){

printf( "%p ", &( m[ i ][ j ] ) );}printf( "\n" );

}printf( "\n" );/* Access by indexing manually */mAlt = &( m[ 0 ][ 0 ] );for( i = 0; i < SIZE; i++ ){

printf( "%2d: ", i );for( j = 0; j < SIZE; j++ ){

printf( "%p ", &( mAlt[ i * SIZE + j ] ) );}printf( "\n" );

}return( 0 );

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi marray.c -o marraypaullu@ug30:~/C201>./marray0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0xbffffa80

0xbffffa84

0xbffffa88

0xbffffa8c

Page 92: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (3)

#include <stdio.h>#define SIZE 2int main( int argc, char ** argv ){

int m[ SIZE ][ SIZE ], * mAlt, i, j;

/* Access like multidimensional array */for( i = 0; i < SIZE; i++ ){

printf( "%2d: ", i );for( j = 0; j < SIZE; j++ ){

printf( "%p ", &( m[ i ][ j ] ) );}printf( "\n" );

}printf( "\n" );

...snip...

C lays out an array in row-major format: onecomplete row, then another row.

FORTRAN is the best known language that

uses column-major format

paullu@ug30:~/C201>makegcc -Wall -ansi marray.c -o marraypaullu@ug30:~/C201>./marray0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0xbffffa80

0xbffffa84

0xbffffa88

0xbffffa8c

Page 93: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (4)

#include <stdio.h>#define SIZE 2int main( int argc, char ** argv ){

int m[ SIZE ][ SIZE ], * mAlt, i, j;

...snip...

/* Access by indexing manually */mAlt = &( m[ 0 ][ 0 ] );for( i = 0; i < SIZE; i++ ){

printf( "%2d: ", i );for( j = 0; j < SIZE; j++ ){

printf( "%p ", &( mAlt[ i * SIZE + j ] ) );}printf( "\n" );

}return( 0 );

} /* main */

If you understand the layout of arrays, you can

do the indexing manually.

paullu@ug30:~/C201>makegcc -Wall -ansi marray.c -o marraypaullu@ug30:~/C201>./marray0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0: 0xbffffa80 0xbffffa841: 0xbffffa88 0xbffffa8c

0xbffffa80

0xbffffa84

0xbffffa88

0xbffffa8c

Page 94: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (5)

#include <stdio.h>#include <stdlib.h>#include <assert.h>

int main( int argc, char ** argv ){

int * mAlt, i, j, size;

size = atoi( argv[ 1 ] );assert( size >= 0 && size < 1024 );

mAlt = malloc( size*size*sizeof(int) );assert( mAlt != NULL );

/* Access by indexing manually */for( i = 0; i < size; i++ ){

printf( "%2d: ", i );for( j = 0; j < size; j++ ){

printf( "%p ",&( mAlt[ i * size + j ] ) );

}printf( "\n" );

}return( 0 );

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi marray.2.c -o marray.2paullu@ug30:~/C201>./marray.2 20: 0x8049808 0x804980c1: 0x8049810 0x8049814

paullu@ug30:~/C201>./marray.2 30: 0x8049808 0x804980c 0x80498101: 0x8049814 0x8049818 0x804981c2: 0x8049820 0x8049824 0x8049828

paullu@ug30:~/C201>./marray.2 -1marray.2: marray.2.c:10: main:Assertion ‘size >= 0 && size < 1024’failed.Abort

Case 2: If the dimensions are not

known until run-time, you can use

malloc() and manual indexing

Page 95: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (6)

#include <stdio.h>#include <stdlib.h>#include <assert.h>int main( int argc, char ** argv ){

int ** mAltPtr, i, j, size;

size = atoi( argv[ 1 ] );assert( size >= 0 && size < 1024 );mAltPtr = malloc( size * sizeof( int * ) );assert( mAltPtr != NULL );

for( i = 0; i < size; i++ ){

mAltPtr[ i ] = malloc( size * sizeof(int) );assert( mAltPtr[ i ] != NULL );

}

/* Access by indexing manually */for( i = 0; i < size; i++ ){

printf( "%2d: ", i );for( j = 0; j < size; j++ ){

printf( "%p ", &( mAltPtr[ i ][ j ] ) );}printf( "\n" );

}return( 0 );

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi marray.3.c -o marray.3paullu@ug30:~/C201>./marray.3 20: 0x8049898 0x804989c1: 0x80498a8 0x80498ac

0x08049898

0x0804988c

0x08049888

0x080498a8

Case 3: You can usearrays-of-arrays and use the samenotation as for staticmultidimensional arrays.

There are storage overheads.

Page 96: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Multidimensional Arrays (7)

#include <stdio.h>#include <stdlib.h>#include <assert.h>int main( int argc, char ** argv ){

char ** mAltPtr;int i, j, size;

size = atoi( argv[ 1 ] );assert( size >= 0 && size < 1024 );mAltPtr = malloc( size * sizeof( char * ) );assert( mAltPtr != NULL );

for( i = 0; i < size; i++ ){

mAltPtr[ i ] = malloc( size * sizeof(char) );assert( mAltPtr[ i ] != NULL );

}/* Access by indexing manually */for( i = 0; i < size; i++ ){

printf( "%2d: ", i );for( j = 0; j < size; j++ ){

printf( "%p ", &( mAltPtr[ i ][ j ] ) );}printf( "\n" );

}return( 0 );

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi marray.4.c -o marray.4paullu@ug30:~/C201>./marray.4 20: 0x8049898 0x80498991: 0x80498a8 0x80498a9

Of course, these techniques workfor types other than integers

Compare this to char ** argv.

I recommend the Case 2technique.

Page 97: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Matrix Multiplication

int a[SIZE][SIZE];int b[SIZE][SIZE];int c[SIZE][SIZE];int i, j, k;float csum;

/* c = a x b */for( i = 0; i < size; i++ ){

for( j = 0; j < size; j++ ){

csum = 0;for( k = 0; k < size; k++ ){

csum += a[i][k] * b[k][j];}c[i][j] = csum;

}}

/* Assume a, b, c are matrix ADTs *//* a is m x n. b is n x p. c is m x p */

int i, j, k;float csum;

/* c = a x b */for( i = 0; i < m; i++ ){

for( j = 0; j < p; j++ ){

csum = 0;for( k = 0; k < n; k++ ){

csum += getElem(a,i,k) * getElem(b,k,j);}setElem(c,i,j,csum);

}}

For Assignment #2, you are likely using linked-listADTs.You can abstract the details of how to find a particularrow and column of a matrix via getElem() andsetElem()

Page 98: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Matrix Addition

int a[SIZE][SIZE];int b[SIZE][SIZE];int c[SIZE][SIZE];int i, j;float csum;

/* c = a + b */for( i = 0; i < size; i++ ){

for( j = 0; j < size; j++ ){

csum = a[i][j] + b[i][j];c[i][j] = csum;

}}

/* Assume a, b, c are matrix ADTs *//* a is m x n. b is m x n. c is m x n */

int i, j;float csum;

/* c = a + b */for( i = 0; i < m; i++ ){

for( j = 0; j < n; j++ ){

csum = getElem(a,i,j) + getElem(b,i,j);setElem(c,i,j,csum);

}}

Matrix addition only has 2 loops.The matrices are all the same size (i.e., m x n)Consider abstracting m,n, p with getNumRows() andgetNumCols()

Page 99: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope

paullu@ug30:~/C201>cat t8.c#include <stdio.h>#include <stdlib.h>

void sub(){

static int i = 2;int j = 1;printf( "&i = %p / %u\n",

&i, (int)&i );printf( " i = %d\n", i );printf( "&j = %p / %u\n",

&j, (int)&j );printf( " j = %d\n", j );i++;j++;

} /* sub */

int main( int argc, char * argv[] ){

sub();sub();sub();return( 0 );

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t8.c -o t8

paullu@ug30:~/C201>./t8&i = 0x8049678 / 134518392i = 2

&j = 0xbffffa84 / 3221224068j = 1

&i = 0x8049678 / 134518392i = 3

&j = 0xbffffa84 / 3221224068j = 1

&i = 0x8049678 / 134518392i = 4

&j = 0xbffffa84 / 3221224068j = 1

The static declarationspecifier (aka modifier)changes a local variable on thestack into a “global” variable inthe data segment.But, only function sub() can“see” the variable i

Page 100: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope (2)

paullu@ug30:~/C201>cat t8.c#include <stdio.h>#include <stdlib.h>

void sub(){

static int i = 2;int j = 1;printf( "&i = %p / %u\n",

&i, (int)&i );printf( " i = %d\n", i );printf( "&j = %p / %u\n",

&j, (int)&j );printf( " j = %d\n", j );i++;j++;

} /* sub */

int main( int argc, char * argv[] ){

sub();sub();sub();return( 0 );

} /* main */

And, since i is now on thedata segment, its values (andchanges to its value) persistacross multiple function calls.Notice how the value of j doesnot persist.Is it possible for other functionsto change the value of i?Is it theoretically possible forlocal variables to keep theirvalues from call-to-call, but arestill on the stack?

Page 101: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope (3)

paullu@ug30:~/C201>cat t8.c#include <stdio.h>#include <stdlib.h>

void sub(){

static int i = 2;#ifdef BONZO

int j = 1;#endif /* BONZO */

int j;printf( "&i = %p / %u\n",

&i, (int)&i );printf( " i = %d\n", i );printf( "&j = %p / %u\n",

&j, (int)&j );printf( " j = %d\n", j );i++;j++;

} /* sub */

int main( int argc, char * argv[] ){

sub();sub();sub();return( 0 );

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t8.c -o t8

paullu@ug30:~/C201>./t8&i = 0x8049678 / 134518392i = 2

&j = 0xbffffa84 / 3221224068j = 134513792

&i = 0x8049678 / 134518392i = 3

&j = 0xbffffa84 / 3221224068j = 134513793

&i = 0x8049678 / 134518392i = 4

&j = 0xbffffa84 / 3221224068j = 134513794

What happens if we removethe = 1 part of int j = 1;?

Page 102: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope (4)

#include <stdio.h>

static struct Node * GlobalHeadOfList = NULL;

int main( int artc, char * argv[] ){

...snip...}

The static declaration specifier (aka modifier) canalso be used with global variablesSuch variables are exactly like other global variables,but they cannot be seen from other source code files,as per separate compilation.

Page 103: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope (5)

Therefore, static helps implement a form ofinformation hiding

1 variables that are only visible within a function:King (pg. 403) describes this as static storage duration,block scope, no linkage

2 variables that are only visible within a separatelycompiled file:King (pg. 403) describes this as static storage duration,file scope, internal linkage

Within an ADT, which is typically within a .c file,consider making as many (previously) global variablesstatic, as possible.

Page 104: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Storage and Scope (6)

#include <stdio.h>

static struct Node * GlobalHeadOfList = NULL;

static int FreeLinkedList( struct Node * head );

int main( int artc, char * argv[] ){

...snip...}

The static declaration specifier (aka modifier) canalso be used with functions.These functions cannot be seen (or called) from othersource code files, as per separate compilation.Compare these concepts to Java’s (and C++’s)much-more sophisticated use of public, private,protected, etc.

Page 105: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Function Pointers

% man qsortQSORT(3) Linux Programmer’s Manual QSORT(3)

NAMEqsort - sorts an array

SYNOPSIS#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,int(*compar)(const void *, const void *));

DESCRIPTIONThe qsort() function sorts an array with nmemb elements ofsize size. The base argument points to the start of thearray.

...The comparison function must return an integer less than,equal to, or greater than zero if the first argument isconsidered to be respectively less than, equal to, orgreater than the second. If two members compare as equal,their order in the sorted array is undefined.

qsort() is a library function that implements thequicksort algorithm.

Page 106: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Function Pointers (2)

#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,int(*compar)(const void *, const void *));

int(*compar)(const void *, const void *)is a function pointer: a pointer to a function.But, compar is not just any function.It must return type int and take a const void * andconst void * as its two parametersIt should do a comparison between two list elements, orelse the algorithm will not work.

Page 107: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Function Pointers (3)

#include <stdlib.h>#define SIZE 128

/*void qsort(void *base, size_t nmemb, size_t size,

int(*compar)(const void *, const void *));

*/

int compare_ints( const void * p, const void * q ){

return( *((int *)p) - *((int *)q) );}

int main( int argc, char * argv[] ){

int a[ SIZE ];

qsort( a, SIZE, sizeof( a[ 0 ] ), compare_ints );

return( 0 );} /* main */

Why is parameter size required?

Page 108: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Function Pointers (4)

#define SIZE 128

struct ClassSortedList {int list[ SIZE ];int(*compar)(const void *, const void *);int(*sortList)();int(*printList)();

};

extern int compareInts(const void *, const void *);extern int sortIntList();extern int printIntList();

int main( int argc, char * argv[] ){

struct ClassSortedList * obj;

obj = (struct ClassSortedList *)calloc(1,sizeof( struct ClassSortedList));assert( obj != NULL );obj->compar = compareInts;obj->sortList = sortIntList;obj->printList = printIntList;obj->printList(); /* Call via function pointer */(*obj->printList)(); /* Call via function pointer */

} /* main */

The concept of function pointers can be used to buildan object.

Page 109: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Function Pointers (5)

From King, pg. 389

void (*file_cmd[])(void) = { new_cmd, /* All _cmd identifiers */open_cmd, /* refer to actual functions */close_cmd,close_all_cmd,save_cmd,save_as_cmd,save_all_cmd,print_cmd,exit_cmd

};

If the user enters an integer n between 0 and 8 (orselects a menu item between 0 and 8), then we can dothis:

assert( 0 <= n && n <= 8 );(*file_cmd[ n ])(); /* or file_cmd[n]() */

How could this have been handled with a switchstatement?

Page 110: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Initialization

We have already seen statements like the following:

int GlobalInt = 1;char * GlobalString = "hello";

int main( int argc, char * argv[] ){

int localInt = 2;char * localString = "hello there";

} /* main */

However, we can also provide initial values tostructures, arrays, and arrays of structures.

Page 111: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Initialization (2)

#include <stdio.h>

struct pair{

int num;int square;

};

struct pair S10 = { 10, 100 };

/* Look-up table */struct pair Squares[] = { {0, 0}, {1,1},

{2,4}, {3,9}, {-1,-1} };

int main( int argc, char * argv[] ){

int i;for( i = 0; Squares[ i ].num != -1; i++ ){

printf( "%2d ^ 2 = %2d\n",i, Squares[ i ].square );

}

return 0;} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t10.c -o t10

paullu@ug30:~/C201>./t100 ^ 2 = 01 ^ 2 = 12 ^ 2 = 43 ^ 2 = 9

Page 112: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Initialization (3)

paullu@ug30:~/C201>cat t11.c#include <stdio.h>

/* Look-up table */int Squares[] = { 0, 1, 4, 9, -1 };

int main( int argc, char * argv[] ){

int i;for( i = 0; Squares[ i ] != -1; i++ ){

printf( "%2d ^ 2 = %2d\n", i, Squares[ i ] );}

return 0;} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t11.c -o t11paullu@ug30:~/C201>./t110 ^ 2 = 01 ^ 2 = 12 ^ 2 = 43 ^ 2 = 9

Page 113: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

The CLanguage (1)Thinking in C

Memory Model

Arrays and Strings inMemory

The CLanguage (2)Linked Lists

MultidimensionalArrays

The CLanguage (3)Storage and Scope

Function Pointers

Initialization

Initialization (4)

paullu@ug30:~/C201>cat t12.c#include <stdio.h>

struct pair{

int num;char * s;

};

/* Look-up table */struct pair Num[] = { {0, "zero"}, {1, "one"},

{2, "two"}, {3, "three"}, {-1, "none"} };

int main( int argc, char * argv[] ){

int i;for( i = 0; Num[ i ].num != -1; i++ ){

printf( "%2d = %s\n", i, Num[ i ].s );}

return 0;} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t12.c -o t12paullu@ug30:~/C201>./t120 = zero1 = one2 = two3 = three

Page 114: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Outline

Part IV

More Examples

9 Examples from Real CodeOpen SourceStorage and ScopeFunction PointersInitializationTest Suites

Page 115: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Open-Source Code

One of the best ways to learn how to write software(and not just “hack code”) is to look at well-writtensoftware packages.It is still best to start learning a new language with atextbook and small examples, but (after that) readingcode can be just as important as writing code.The open-source code phenomenon makes this easierthan ever.

1 http://www.gnu.org/2 http://freshmeat.net/3 http://sourceforge.net/

Page 116: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat

We will look (briefly) at the source code for the catprogram, since you already know how to use it.

http://directory.fsf.org/textutils.html

cat is a (typically) simple, but extremely useful Unixapplication

1 It does a small number of functions very well2 It is often used as part of a Unix pipeline:

cat -n file1 file2 file3 | grep something > output.file

3 It is part of the GNU text and core utilities package:millions of computers have and use it

Page 117: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (2)

Tar files are often used for distributing open-sourcesoftware:paullu@ug30:~/C201/Cat>tar xvfz textutils-2.1.tar.gztextutils-2.1/textutils-2.1/config/textutils-2.1/config/ChangeLogtextutils-2.1/config/config.guess...snip...textutils-2.1/djgpp/getconftextutils-2.1/djgpp/edtests.battextutils-2.1/djgpp/tscript.sed

The contents of the tar files, especially GNU packages,follow predictable patterns (which is good):paullu@ug30:~/C201/Cat>cd textutils-2.1/home/dsk05/prof/paullu/C201/Cat/textutils-2.1paullu@ug30:~/C201/Cat/textutils-2.1>lsABOUT-NLS GNUmakefile Makefile.in THANKS config.hin doc/ po/AUTHORS INSTALL Makefile.maint TODO configure* lib/ src/COPYING Makefile.am NEWS aclocal.m4 configure.ac m4/ tests/ChangeLog Makefile.cfg README config/ djgpp/ man/paullu@ug30:~/C201/Cat/textutils-2.1>

Page 118: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (3)

It is a good idea to always read the README andINSTALL files

1 Comments on compatibility on different systems andcompilers

2 Note that man pages are part of the distribution3 GNU (and many other) software packages use the

Autoconf tool to help package and customize softwarefor different systems:paullu@ug30:~/C201/Cat/textutils-2.1>./configurechecking build system type... i686-pc-linux-gnuchecking host system type... i686-pc-linux-gnuchecking for a BSD-compatible install... /usr/bin/ginstall -cchecking whether build environment is sane... yeschecking for gawk... gawkchecking whether make sets ${MAKE}... yeschecking for perl5.003 or newer... yeschecking for gcc... gccchecking for C compiler default output... a.out...many lines...config.status: creating Makefileconfig.status: creating doc/Makefileconfig.status: creating lib/Makefile...many lines...

Page 119: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (4)

Autoconf/configure creates the Makefiles (usingautomake)Typically, with packages that use Autoconf (readINSTALL) one does:./configure./make./make check./make install

paullu@ug30:~/C201/Cat/textutils-2.1>make check...snip...Making check in cutmake[2]: Entering directory ‘/home/dsk05/prof/paullu/C201/Cat/textutils-2.1/tests/cut’make check-TESTSmake[3]: Entering directory ‘/home/dsk05/prof/paullu/C201/Cat/textutils-2.1/tests/cut’PASS: cut-tests==================All 1 tests passed==================...snip...

Page 120: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (5)

Explore how an application is built before modifying anycode:paullu@ug30:~/C201/Cat/textutils-2.1>cd srcpaullu@ug30:~/C201/Cat/textutils-2.1/src>rm catpaullu@ug30:~/C201/Cat/textutils-2.1/src>make -n catrm -f catgcc -g -O2 -o cat cat.o ../lib/libfetish.a ../lib/libfetish.a

paullu@ug30:~/C201/Cat/textutils-2.1/src>cd ../libpaullu@ug30:~/C201/Cat/textutils-2.1/lib>ls *.alibfetish.apaullu@ug30:~/C201/Cat/textutils-2.1/lib>rm libfetish.apaullu@ug30:~/C201/Cat/textutils-2.1/lib>makemake all-amrm -f libfetish.aar cru libfetish.a acl.o getdate.o posixtm.o posixver.o strftime.ogetopt.o getopt1.o hash.o hash-pjw.o addext.o argmatch.o backupfile.o...snip...ranlib libfetish.a

1 make -n shows you the actions that would be taken,but does not actually execute any commands/actions

2 -O2 sets the level of compiler optimization3 Separate compilation is used to create .o files for a

library

Page 121: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (6)

How large should one make .c files and modules?Answer: As large are they need to be, but no larger.paullu@ug30:~/C201/Cat/textutils-2.1/lib>wc *.c | sort -r35691 142094 986526 total8433 33390 261021 regex.c2315 9312 63104 getdate.c1406 5027 34534 strftime.c1189 4243 29183 fnmatch_loop.c1086 3923 26796 getloadavg.c1068 4516 30584 getopt.c1047 4169 30574 hash.c807 2706 20239 mountlist.c658 2536 17443 quotearg.c623 2849 19175 obstack.c528 2470 15118 mktime.c

...snip...26 157 940 memset.c22 147 903 strtoul.c14 53 324 atexit.c4 13 110 xstrtoul.c2 5 42 strtoumax.c2 4 45 strncasecmp.c

ar and ranlib are common utilities to create libraries(i.e., libfetish.a);

Page 122: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

cat (7)

Dealing with cross-platform issues is a commonconcernpaullu@ug30:~/C201/Cat/textutils-2.1/lib>cat atexit.c/* Wrapper to implement ANSI C’s atexit using SunOS’s on_exit. *//* This function is in the public domain. --Mike Stump. */

#include "config.h"

intatexit(f)

void (*f)();{

/* If the system doesn’t provide a definition for atexit, use on_exitif the system provides that. */

on_exit (f, 0);return 0;

}

Page 123: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Storage and Scope

Recall that static is a way to enforce informationhidingIn addition to your editor, debugger, Makefiles, andvalgrind, your Unix friends include:

1 Automation: Shell aliases (C shell here)setenv VISUAL vimalias viM "$VISUAL Makefile"alias mc "make clean"

2 Finding things: grep, egrep, xargs3 Text utilities: cat, wc, xargs

I often use the following C shell aliases:alias vruses ’alias vruses; vim ‘find . \( -name "*.c" -o -name "*.h"-o -name "make*" -o -name "Make*" \) -print | grep -v Archive |xargs egrep -l \!:1‘’%% Usage: vruses static

alias lsf "find . -print"%% Usage: lsf | grep somethingInFilename

Page 124: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Storage and Scope (2)

How many uses of static are there?paullu@ug30:~/C201/Cat/textutils-2.1>find . \( -name "*.c" -o -name "*.h"-o -name "make*" -o -name "Make*" \) -print | grep -v Archive |xargs egrep -l static./lib/alloca.c./lib/dup2.c./lib/error.c...snip..../src/wc.c./src/tac-pipe.c./config.h

paullu@ug30:~/C201/Cat/textutils-2.1>find . \( -name "*.c" -o -name "*.h"-o -name "make*" -o -name "Make*" \) -print | grep -v Archive |xargs egrep -l static | wc

86 86 1321

paullu@ug30:~/C201/Cat/textutils-2.1>find . \( -name "*.c" -o -name "*.h"-o -name "make*" -o -name "Make*" \) -print | grep -v Archive |xargs egrep -l ’^static’ | wc

71 71 1080

There are approximately 71 static functions and staticglobal variables.

Page 125: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Storage and Scope (3)

Look at lib/error.cstatic char *private_strerror (int errnum){

extern char *sys_errlist[];extern int sys_nerr;

if (errnum > 0 && errnum <= sys_nerr)return _(sys_errlist[errnum]);

return _("Unknown system error");}

The function can only be called within error.c

Notice that you can use extern within a functiondefinition; keep the declarations close to the use-site

Page 126: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Storage and Scope (4)

Look at lib/error.c (with some cleanups):static voidprint_errno_message (int errnum){

char const *s;

char errbuf[1024];s = strerror (errnum);

if (_IO_fwide (stderr, 0) > 0){

__fwprintf (stderr, L": %s", s);return;

}

fprintf (stderr, ": %s", s);}

Another private method/function.

Page 127: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Storage and Scope (5)

Look at lib/error.c, inside functionerror_at_line()

if (error_one_per_line){

static const char *old_file_name;static unsigned int old_line_number;

if (old_line_number == line_number&& (file_name == old_file_name

|| strcmp (old_file_name, file_name) == 0))/* Simply return and print nothing. */return;

old_file_name = file_name;old_line_number = line_number;

}

fflush (stdout);

Using a static local variable to “remember” informationfrom the last invocationNotice the use of fflush(stdout) to force buffers toempty

Page 128: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Function Pointers

We saw the use of function pointers in the C library’sqsort() and in the text utilities lib/atexit.c’satexit()

There is also a generic hash table implementation inlib/hash.h:typedef unsigned (*Hash_hasher) PARAMS ((const void *, unsigned));typedef bool (*Hash_comparator) PARAMS ((const void *, const void *));typedef void (*Hash_data_freer) PARAMS ((void *));typedef bool (*Hash_processor) PARAMS ((void *, void *));

Another use is to provide a default function:/* Process long options --help and --version, but only if argc == 2.

Be careful not to gobble up ‘--’. */

voidparse_long_options (int argc,

char **argv,const char *command_name,const char *package,const char *version,const char *authors,void (*usage_func)())

{

Page 129: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Function Pointers (2)

As with Java’s interface mechanism (andqsort()), sets and arrays of function pointers are away to specify an interface for which the user mustprovide implementationsIn a research paper:Providing Tunable Consistency for a Parallel File Store

by Murali Vilayannur, Partho Nath, and AnandSivasubramaniam

to appear at the Fourth USENIX Conference on Fileand Storage Technologies, December 2005.

the authors describe a file system that allows the userto customize what the system does in response toshared files (a problem of consistency)

Page 130: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Function Pointers (3)

The authors’ approach is based on custom libraries andfunction pointersstruct plugin_policy_ops {

handle (*pre_open)(force_commit, use_hcache, hcache_coherence,delay_commit, num_hashes);

int (*post_open)(void *handle);int (*pre_close)(void *handle);int (*post_close)(void *handle);int (*pre_read)(void *handle, size, offset);int (*post_read)(void *handle, size, offset);int (*pre_write)(void *handle, size, offset, int *delay_wc);int (*post_write)(void *handle, sha1_hashes *old, sha_hashes *new);int (*pre_sync)(const char *);int (*post_sync)(void *handle);

};

for specifying the Client-Side Plug-in API (Figure 6 fromthe paper)This basic technique is also used in the Virtual FileSystem (VFS) kernel interface of Linux and other OSes

Page 131: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Initialization

In src/cat.c, a character array is used to pre-formatline numbers for output (see cat -n):/* Buffer for line numbers.

An 11 digit counter may overflow within an hour on a P2/466,an 18 digit counter needs about 1000y */

#define LINE_COUNTER_BUF_LEN 20static char line_buf[LINE_COUNTER_BUF_LEN] =

{’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’,’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’ ’, ’0’,’\t’, ’\0’

};

/* Position in ‘line_buf’ where printing starts. This will not changeunless the number of lines is larger than 999999. */

static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;

/* Position of the first digit in ‘line_buf’. */static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;

/* Position of the last digit in ‘line_buf’. */static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;

Why not just use sprintf()?

Page 132: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Initialization (2)

In lib/getopt.h (with some clean up):struct option{

const char *name;/* has_arg can’t be an enum because some compilers complain about

type mismatches in all the code that assumes it is an int. */int has_arg;int *flag;int val;

};

In src/cat.cstatic struct option const long_options[] ={

{"number-nonblank", no_argument, NULL, ’b’},{"number", no_argument, NULL, ’n’},{"squeeze-blank", no_argument, NULL, ’s’},{"show-nonprinting", no_argument, NULL, ’v’},{"show-ends", no_argument, NULL, ’E’},{"show-tabs", no_argument, NULL, ’T’},{"show-all", no_argument, NULL, ’A’},

#if O_BINARY{"binary", no_argument, NULL, ’B’},

#endif{GETOPT_HELP_OPTION_DECL},{GETOPT_VERSION_OPTION_DECL},{NULL, 0, NULL, 0}

};

Page 133: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Initialization (3)

In lib/getopt1.c:intmain (argc, argv)

int argc;char **argv;

{int c;int digit_optind = 0;

while (1){

int this_option_optind = optind ? optind : 1;int option_index = 0;static struct option long_options[] ={

{"add", 1, 0, 0},{"append", 0, 0, 0},{"delete", 1, 0, 0},{"verbose", 0, 0, 0},{"create", 0, 0, 0},{"file", 1, 0, 0},{0, 0, 0, 0}

};

c = getopt_long (argc, argv, "abc:d:0123456789",long_options, &option_index);

Again, we see the principle of “declare or definesomething near where you use it”.

Page 134: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Initialization (4)

In a unrelated program that computes cyclicredundancy check (CRC) codes, a look-up table isused:static UNS_32_BITS crc_32_tab[] = { /* CRC polynomial 0xedb88320 */0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,0x706af48f, 0xe963a535, 0x9e6495a3,0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b,0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,

...snip...0xcdd70693, 0x54de5729, 0x23d967bf,0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37,0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};

#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc)>>8))

Look-up tables can significantly speed-up certaincalculations and algorithms.http://en.wikipedia.org/wiki/Cyclic_redundancy_check

Page 135: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Test Suites

Validation and correctness testing are key to qualitysoftware. Quality is always important, but especiallywhen:

1 Lives depend on it, as in health care or critical softwaresystems for nuclear power plants, airplanes, etc.

2 Many other software systems depend on it (e.g., thecompiler, the Standard C library)

Performance testing and benchmarking are alsoimportant. But, that’s a topic to consider aftercorrectness.

Page 136: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Test Suites (2)

Fifth Dimension Information Systems(http://www.5d.ca/) is an Edmonton company thatdevelops software for “regulated industries”, includinghealth care

1 At an IIP reception, the President of 5D said that one oftheir products has 2.5 quality assurance people forevery 4 developers.

2 A job posting for a Software Quality Assurance (SQA)Specialist required:

“Creates, reviews and maintains product releasedocumentation including, but is not limited to, the DeviceHistory Record (DHR) and the Device Master Record(DMR).”“Writing and executing test scenarios.”

Page 137: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Test Suites (3)

Compilers must be carefully tested, because if they arewrong, then many other pieces of software will bewrong too.Developers of commercial compilers have their own,internal compiler test programs (including the compileritself).Some companies make a business of selling testsuites. For example:

1 The Plum Hall Validation Suite for C(http://www.plumhall.com/stec.html)

Over 56,000 lines of code2 The Open Group (a standards body) also has test

suites (some cost $20,000 for a 10 year licence and$10,000 per year for support)

ACVS, CVSA, C++VS (over 73,000 tests for C++)

Page 138: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Examplesfrom RealCodeOpen Source

Storage and Scope

Function Pointers

Initialization

Test Suites

Test Suites (4)

The GNU developers of gcc have their own test suitesand benchmarks.

1 http://gcc.gnu.org/testing/2 http://gcc.gnu.org/onlinedocs/gccint/

C-Tests.html3 http://www.toolchain.org/testresults/

The developers of gcc (and all compilers) have toworry about

1 All aspects of the C language2 All compiler options, especially optimization options

In addition, gcc has to deal with1 Different underlying operating systems (e.g., Linux,

OpenBSD, MacOS/BSD)2 Different CPU instruction sets

Testing is absolutely vital!

Page 139: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Outline

Part V

Understanding C

10 Understanding the C Compiler

11 Low-Level C LanguageParameter PassingCompiler OptimizationsBitwise OperatorsBit Fields

12 Review: Layers of Abstraction

Page 140: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Understanding the C Compiler

The main phases of the C compiler are:1 Preprocessing

Lexically insert #include files, #define macros, gcc-D definitions

2 Compiling1 Translating from the C language into executable code2 Optimizing: Transform the code into equivalent code that

is faster3 Assembling: Translate the assembly code to

CPU-specific machine code3 Linking

Find all library and extern code4 Loading (partly the compiler, partly the OS)

In memory, resolve (aka bind) all function and variableaddresses.

Page 141: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing

Preprocessing1 Lexically insert #include files, #define macros,

gcc -D definitions2 Resolve conditional compilation

“Lexically insert” means “adding data withoutinterpreting the contents”

paullu@ug30:~/C201>cat t14.c#define SIZE = 128 /**** WRONG ****/

int main( int argc, char * argv[] ){

int i = SIZE;return 0;

} /* main */

paullu@ug30:~/C201>gcc -E -Wall -ansi t14.c# 1 "t14.c"# 1 "<built-in>"# 1 "<command line>"# 1 "t14.c"int main( int argc, char * argv[] ){

int i = = 128;return 0;

}

paullu@ug30:~/C201>gcc -Wall -ansi t14.ct14.c: In function ‘main’:t14.c:5: error: parse error before ’=’ tokent14.c:5: warning: unused variable ‘i’

Page 142: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (2)

The gcc -E command-line argument is useful fordebugging issues related to the preprocessor: it stopsthe process after the preprocessor phase and sendsthe output to gcc’s Standard OutBecause the preprocessor phase does NOT interpretthe data, we can use the preprocessor for thingscompletely unrelated to C programming.One could “factor out” common text into a file andinclude that file whenever and wherever needed

Page 143: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (3)

unix-prompt% cat publications.h<HTML><HEAD><TITLE>Paul Lu’s (Selected) Publications</TITLE></HEAD><BODY bgcolor="#ffffff" text="#000000">

<H3>Selected Publications (by date):</H3>

<OL><p><b>2005</b><p><LI>#include <pa-gosub.nar.2005.h><BR><BR></LI>...snip...

unix-prompt% gcc -E -I./Citations -I. -P publications.h |sed -f sed.remove.trailing.quote > publications.html

unix-prompt% cat Citations/pa-gosub.nar.2005.h<b>[ NEW ]</b> Paul Lu, Duane Szafron, Russell Greiner, David S. Wishart,Alona Fyshe, Brandon Pearcy, Brett Poulin, Roman Eisner, Danny Ngo, andNicholas Lamb....snip...

Page 144: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (4)

unix-prompt% cat cvpublications.h<HTML><HEAD><TITLE>Paul Lu’s (Selected) Publications: By Type</TITLE></HEAD>

<H3>Selected Publications (by type):</H3><H4>Refereed Journals:</H4>

<OL>

<LI>#include <pa-gosub.nar.2005.h><BR><BR></LI>...snip...

unix-prompt% gcc -E -I./Citations -I. -P cvpublications.h |sed -f sed.remove.trailing.quote > cvpublications.html

I can re-use the bibliographical information for thispaper in many places, without having to cut-and-pasteFor non-trivial HTML pages, I recommend that you usedifferent tools!

Page 145: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (5)

Macros can take arguments (from King pg. 279):paullu@ug30:~/C201>cat t15.c#define MAX(x,y) ( (x) > (y) ? (x) : (y) )#define IS_EVEN(n) ( (n) % 2 == 0 )

int main( int argc, char * argv[] ){

int i, x, y;i = MAX( x + y, x - y );if( IS_EVEN( i ) )

i++;return 0;

} /* main */

paullu@ug30:~/C201>gcc -E -Wall -ansi t15.c# 1 "t15.c"# 1 "<built-in>"# 1 "<command line>"# 1 "t15.c"int main( int argc, char * argv[] ){

int i, x, y;i = ( (x + y) > (x - y) ? (x + y) : (x - y) );if( ( (i) % 2 == 0 ) )

i++;return 0;

}

Page 146: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (6)

/usr/include is the standard location for most#include <...> header filesInside /usr/include/assert.h (cleaned up):# define __ASSERT_VOID_CAST (void)

#ifdef NDEBUG# define assert(expr) (__ASSERT_VOID_CAST (0))#else /* Not NDEBUG. */

/* This prints an "Assertion failed" message and aborts. */extern void __assert_fail (__const char *__assertion, __const char *__file,

unsigned int __line, __const char *__function)__THROW __attribute__ ((__noreturn__));

# define assert(expr) \(__ASSERT_VOID_CAST ((expr) ? 0 : \

(__assert_fail (__STRING(expr), __FILE__, __LINE__, \__ASSERT_FUNCTION), 0)))

# endif

NDEBUG is discussed in man assert

__FILE__, __LINE__ are compile-time macrosprovided by gcc

Page 147: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (7)

Using assertions is relatively easypaullu@ug30:~/C201>cat t16.c#include <assert.h>

int main( int argc, char * argv[] ){

assert( 0 );return 0;

} /* main */

paullu@ug30:~/C201>gcc -Wall -ansi t16.c

paullu@ug30:~/C201>a.outa.out: t16.c:5: main: Assertion ‘0’ failed.Abort (core dumped)

Page 148: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (8)

paullu@ug30:~/C201>gcc -E -Wall -ansi t16.c# 1 "t16.c"# 1 "<built-in>"# 1 "<command line>"# 1 "t16.c"# 1 "/usr/include/assert.h" 1 3 4# 36 "/usr/include/assert.h" 3 4# 1 "/usr/include/features.h" 1 3 4# 308 "/usr/include/features.h" 3 4# 1 "/usr/include/sys/cdefs.h" 1 3 4# 309 "/usr/include/features.h" 2 3 4# 331 "/usr/include/features.h" 3 4# 1 "/usr/include/gnu/stubs.h" 1 3 4# 332 "/usr/include/features.h" 2 3 4# 37 "/usr/include/assert.h" 2 3 4# 65 "/usr/include/assert.h" 3 4

extern void __assert_fail (__const char *__assertion, __const char *__file,unsigned int __line, __const char *__function)

__attribute__ ((__nothrow__)) __attribute__ ((__noreturn__));extern void __assert_perror_fail (int __errnum, __const char *__file,

unsigned int __line,__const char *__function)

__attribute__ ((__nothrow__)) __attribute__ ((__noreturn__));extern void __assert (const char *__assertion, const char *__file, int __line)

__attribute__ ((__nothrow__)) __attribute__ ((__noreturn__));

Page 149: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (9)

# 2 "t16.c" 2int main( int argc, char * argv[] ){

((void) ((0) ? 0 : (__assert_fail ("0", "t16.c", 5, __PRETTY_FUNCTION__), 0)));return 0;

}

Notice:

You can find out where your header files are locatedYou can see all the macros, after they have beenexpandedYou can see the results of conditional compilation

Page 150: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (10)

Conditional compilation is used to selectively includecode.One common use is to turn on/off debugging code.We have seen the simplistic form:

for( i = 0; Num[ i ].num != -1; i++ ){

sum += Num[ i ].s;#ifdef DEBUG

printf( "%2d = %s\n", i, Num[ i ].s );#endif /* DEBUG */

}

Page 151: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Preprocessing (11)

Another use of conditional compilation is dealing withcross-platform issues (from cat.c)#ifdef FIONREAD

int n_to_read = 0;

/* Is there any input to read immediately?If not, we are about to wait,so write all buffered output before waiting. */

if (use_fionread&& ioctl (input_desc, FIONREAD, &n_to_read) < 0)

{/* Ultrix returns EOPNOTSUPP on NFS;

HP-UX returns ENOTTY on pipes.SunOS returns EINVAL andMore/BSD returns ENODEV on special fileslike /dev/null.Irix-5 returns ENOSYS on pipes. */

if (errno == EOPNOTSUPP || errno == ENOTTY|| errno == EINVAL || errno == ENODEV

# ifdef ENOSYS|| errno == ENOSYS

# endif)

use_fionread = 0;else

{error (0, errno, _("cannot do ioctl on ‘%s’"), infile);exit_status = 1;newlines2 = newlines;return;

}}

if (n_to_read == 0)#endif

Page 152: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing

Function parameters are like local variables in terms oftheir storage and persistence.One must know the responsibilities of the caller andcalleeFor parameters, the caller (at the call site):

1 Allocates space on the stack, before the call2 Initializes the value(s)3 Deallocates space on the stack, after the call4 Provides a return address

For other local variables, the callee (i.e., the function):1 Allocates space on the stack, before the function’s body2 Initializes the value(s), before the function’s body3 Deallocates space on the stack, after the function’s

body

Page 153: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing (2)

The set of fields on the stack for1 Parameters2 Local variables3 Return addresses4 Saved CPU register values (for both caller and callee),

especially the stack pointer5 Other stuff

is known as the activation record or stack frame.The details of the activation record are highlydependent on

1 the CPU architecture2 the compiler3 the application binary interface (ABI)

Exam question: Why is an ABI important for code libraries?

Page 154: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing (3)

paullu@ug30:~/C201>cat t17.cvoid sub( int a, int b ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, 2 );return 0;

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi -S t17.c

The -S compiler flag leaves the .s files around for usto see (and to learn from).To understand the compilation process, play with the-E, -S, and -v flags.http://en.wikibooks.org/wiki/Programming:x86_assembly

Page 155: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing (4)

paullu@ug30:~/C201>cat t17.s.file "t17.c".text

.globl sub.type sub, @function

sub:pushl %ebpmovl %esp, %ebpmovl 12(%ebp), %eaxmovl %eax, 8(%ebp)popl %ebpret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $8, %esppushl $2pushl $1call subaddl $16, %espmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

The next few slides are necessarily a mess.x86 ESP : Top of Stack Pointer. Changed implicitly.x86 EBP : Stack Base Pointer.Instruction format: movl source,target

Page 156: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing (5)

sub(): ebp

main(): ebp

High Memory(4 bytes per block)

Parameter: b=2 12(%ebp)

Parameter: a=1 8(%ebp)

Return Addr main() 4(%ebp)

0(%ebp)

paullu@ug30:~/C201>cat t17.cvoid sub( int a, int b ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, 2 );return 0;

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi -S t17.cpaullu@ug30:~/C201>cat t17.s

.file "t17.c"

.text

.globl sub.type sub, @function

sub:pushl %ebp # Save stack pointer on stackmovl %esp, %ebp # Old top of stack is new basemovl 12(%ebp), %eax # Read variable bmovl %eax, 8(%ebp) # Write to variable apopl %ebp # Restore original stack pointerret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebp # Save the stack pointer on stackmovl %esp, %ebp # Old top of stack is new base

subl $8, %esp # Grow stack 8 bytes; not sure whyandl $-16, %esp # Masking: align stack to 16-bytesmovl $0, %eax # Will be optimized outsubl %eax, %esp # Will be optimized out

subl $8, %esp # Force alignment to 16-bytespushl $2 # Parameter: Constant 2pushl $1 # Parameter: Constant 1call sub # Call the subroutineaddl $16, %esp # Remove rest of activation recordmovl $0, %eax # return 0leaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 157: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing: Initialize from Variables (6)

Param: c=argv

High Memory(4 bytes per block)

sub(): ebp

Return Addr main()

Parameter: a=1

0(%ebp)

4(%ebp)

8(%ebp)

12(%ebp)

16(%ebp)

main(): ebp

Return Addr

0(%ebp)

4(%ebp)

8(%ebp)

12(%ebp)

Parameter: argc

Parameter: argv

Param: b=argc

paullu@ug30:~/C201>cat t18.cvoid sub( int a, int b, char ** c ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, argc, argv );return 0;

} /* main */

paullu@ug30:~/C201>makegcc -Wall -ansi -S t18.cpaullu@ug30:~/C201>cat t18.s

.file "t18.c"

.text.globl sub

.type sub, @function

sub:pushl %ebp # Save stack pointermovl %esp, %ebpmovl 12(%ebp), %eax # Read variable bmovl %eax, 8(%ebp) # Write to variable apopl %ebp # Restore stack pointerret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebp # Save stack pointermovl %esp, %ebpsubl $8, %esp # Grow stack pointerandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $4, %esp # Force alignment to 16-bytespushl 12(%ebp) # Parameter: argvpushl 8(%ebp) # Parameter: argcpushl $1 # Parameter: Constant 1call subaddl $16, %esp # Remove rest of activation recordmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 158: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing: Pointers (7)

paullu@ug30:~/C201>cat t19.cvoid sub( int a, int * b, char ** c ){

a = *b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, &argc, argv );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi -S t19.c

paullu@ug30:~/C201>cat t19.s.file "t19.c".text

.globl sub.type sub, @function

sub:pushl %ebpmovl %esp, %ebpmovl 12(%ebp), %eaxmovl (%eax), %eax # *bmovl %eax, 8(%ebp)popl %ebpret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $4, %esppushl 12(%ebp)leal 8(%ebp), %eax # &argcpushl %eax # Put on stackpushl $1call subaddl $16, %espmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 159: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing: Variable Arguments (8)

See King, pg. 563

paullu@ug30:~/C201>cat t20.cvoid sub( int a, int * b, char ** c, ... ){} /* sub */

int main( int argc, char * argv[] ){

sub( 1, &argc, argv, 2, &argc );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi -S t20.cpaullu@ug30:~/C201>cat t20.s

.file "t20.c"

.text.globl sub

.type sub, @functionsub:

pushl %ebpmovl %esp, %ebppopl %ebpret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $12, %espleal 8(%ebp), %eax # &argcpushl %eaxpushl $2 # Constant 2pushl 12(%ebp) # argvleal 8(%ebp), %eax # &argcpushl %eaxpushl $1 # Constant 1call subaddl $32, %espmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 160: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing: Local Variables (9)

Local: c

High Memory(4 bytes per block)

main(): ebp

Return Addr

0(%ebp)

4(%ebp)

8(%ebp)

12(%ebp)

Parameter: argc

Parameter: argv

Parameter: a=1Return Addr main()

sub(): ebp

8(%ebp)4(%ebp)

0(%ebp)

−4(%ebp)

−8(%ebp)

Local: b

paullu@ug30:~/C201>cat t21.cvoid sub( int a ){

int b, c;b = a;c = a;

} /* sub */

int main( int argc, char * argv[] ){

sub( 1 );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi -S t21.cpaullu@ug30:~/C201>cat t21.s

.file "t21.c"

.text

.globl sub.type sub, @function

sub:pushl %ebpmovl %esp, %ebpsubl $8, %esp # Grow stack for localsmovl 8(%ebp), %eax # Read amovl %eax, -4(%ebp) # Write bmovl 8(%ebp), %eax # Read amovl %eax, -8(%ebp) # Write cleaveret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $12, %esppushl $1 # Constant 1call subaddl $16, %espmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 161: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Parameter Passing (10)

Recall the old theme: C is a high-level assemblylanguageThere is a clear, simple mapping from C to assemblylanguage for

1 function callsactivation records, call

2 parameter passing and local variablesstack-based: pushlstack-relative addressing: arguments (e.g., 12(%ebp), )stack-relative addressing: local variables (e.g.,-8(%ebp), )

3 address-of operator (&)Load effective address: leal 8(%ebp),%eax

4 dereferencing (*)Register indirect addressing: movl (%eax), %eax

Page 162: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Compiler Optimizations

Recall the old theme: Write clear code instead of clevercodeModern compilers can usually do a better job ofimproving your code’s performance than you

Human programmer should focus on algorithmiccomplexity, good data structures, good design, goodtesting, good GUI, etc.Compiler focuses on code optimization

Compiler optimizations are a huge topic of study. Wewill only consider a few simple cases.

Page 163: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Compiler Optimizations: sub(), -O option (2)

paullu@ug30:~/C201>cat t17.cvoid sub( int a, int b ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, 2 );return 0;

} /* main */

ug30:~/C201>gcc -Wall -ansi -S t17.cug30:~/C201>cat t17.s

.file "t17.c"

.text.globl sub

.type sub, @functionsub:

pushl %ebpmovl %esp, %ebpmovl 12(%ebp), %eaxmovl %eax, 8(%ebp)popl %ebpret.size sub, .-sub

...snip...

ug30:~/C201>gcc -Wall -ansi -O -S t17.cug30:~/C201>cat t17.s

.file "t17.c"

.text.globl sub

.type sub, @functionsub:

pushl %ebpmovl %esp, %ebppopl %ebpret.size sub, .-sub

...snip...

Page 164: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Compiler Optimizations: main(), -O option (3)

int main( int argc, char * argv[] ){

sub( 1, 2 );return 0;

} /* main */

ug30:~/C201>gcc -Wall -ansi -S t17.cug30:~/C201>cat t17.s...snip...main:

pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $8, %esppushl $2pushl $1call subaddl $16, %espmovl $0, %eaxleaveret

...snip...

ug30:~/C201>gcc -Wall -ansi -O -S t17.cug30:~/C201>cat t17.s...snip...main:

pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espsubl $8, %esppushl $2pushl $1call subaddl $16, %espmovl $0, %eaxmovl %ebp, %esppopl %ebpret

...snip...

Page 165: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Compiler Optimizations: -03 (4)

paullu@ug30:~/C201>cat t17.cvoid sub( int a, int b ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, 2 );return 0;

} /* main */

paullu@ug30:~/C201>gcc -Wall -ansi -O3 -S t17.cpaullu@ug30:~/C201>cat t17.s

.file "t17.c"

.text

.p2align 4,,15.globl main

.type main, @functionmain:

pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl %ebp, %esp # call sub is gone!xorl %eax, %eaxpopl %ebpret.size main, .-main.p2align 4,,15

.globl sub.type sub, @function

sub:pushl %ebp # But sub exists!movl %esp, %ebppopl %ebpret.size sub, .-sub.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 166: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Compiler Optimizations: while removed (5)

paullu@ug30:~/C201>cat t23.cvoid sub( int a, int b, char ** c ){

a = b;} /* sub */

int main( int argc, char * argv[] ){

sub( 1, argc, argv );argc = argc;while( 0 );return 0;

} /* main */paullu@ug30:~/C201>gcc -Wall -ansi -S t23.cpaullu@ug30:~/C201>cat t23.s

.file "t23.c"

.text.globl sub

.type sub, @functionsub:

pushl %ebpmovl %esp, %ebpmovl 12(%ebp), %eaxmovl %eax, 8(%ebp)popl %ebpret.size sub, .-sub

.globl main.type main, @function

main:pushl %ebpmovl %esp, %ebpsubl $8, %espandl $-16, %espmovl $0, %eaxsubl %eax, %espsubl $4, %esppushl 12(%ebp)pushl 8(%ebp)pushl $1call subaddl $16, %espmovl $0, %eaxleaveret.size main, .-main.section .note.GNU-stack,"",@progbits.ident "GCC: (GNU) 3.3.4"

Page 167: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Bitwise Operators

See King, Chapter 20, page 451Some applications require the ability to manipulatevariables at the level of the binary digit, or bit.

1 Operating systems2 Device drivers (e.g., peripheral registers)3 Networking code4 Space-efficient data structures5 Image processing

Do not confuse bitwise operators (e.g., &) with logicaloperators (e.g., &&). To C’s discredit, it will not alwayswarn you when you are doing something wrong.There is a direct mapping to assembly-languagebitwise instructions.

Page 168: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Bitwise Operators (2)

Bitwise shiftop1 « op2: Left-shift op1 by op2 bitsop1 » op2: Right-shift op1 by op2 bits

paullu@ug30:~/C201>cat t24.c#include <stdio.h>

int main( int argc, char * argv[] ){

int i = 0x0001;printf( "1: %x %x %x\n", i, i << 1, i << 2 );i = 0x000a;printf( "2: %x %x %x\n", i, i << 1, i << 2 );i = 0x0010;printf( "3: %x %x %x\n", i, i >> 1, i >> 2 );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t24.cpaullu@ug30:~/C201>./a.out1: 1 2 42: a 14 283: 10 8 4

Bitwise shifts are often used to create bit masks and tomanipulate graphics

Page 169: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Bitwise Operators (3)

Other bitwise operators:~ op1: Logical negation/complement of op1op1 & op2: Logical and op1 with op2op1 ^ op2: Logical exclusive or (XOR) op1 and op2op1 | op2: Logical inclusive or op1 and op2

paullu@ug30:~/C201>cat t25.c#include <stdio.h>int main( int argc, char * argv[] ){

unsigned int i = 1;printf( "1: %x %x %x\n", i, ~i, ~~i );printf( "2: %x %x \n", i, ( 0x0100 & ( 1 << 8 ) ) >> 8 );printf( "3: %x %x \n", i, 0x0100 ^ ( 1 << 8 ) );printf( "4: %x %x \n", i, 0x0100 | ( 1 << 4 ) );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t25.cpaullu@ug30:~/C201>./a.out1: 1 fffffffe 12: 1 13: 1 04: 1 110

In combination, these operators are used to test,extract, and pack bits.

Page 170: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Bit Fields

Bit fields allow the programmer to control how manybits are used to represent variables. But, be careful ofoverflow.paullu@ug30:~/C201>cat t26.c#include <stdio.h>

struct file_date { /* From King */unsigned int day: 5;unsigned int month: 4;unsigned int year: 7;

};

int main( int argc, char * argv[] ){

struct file_date xm = { 25, 12, 05 };printf( "1: d=%d m=%d y=%d\n", xm.day, xm.month, xm.year );xm.day += 10;printf( "2: d=%d m=%d y=%d\n", xm.day, xm.month, xm.year );printf( "3: size = %d\n", sizeof( xm ) );return 0;

} /* main */paullu@ug30:~/C201>makegcc -Wall -ansi t26.cpaullu@ug30:~/C201>./a.out1: d=25 m=12 y=52: d=3 m=12 y=53: size = 4

Page 171: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

Understandingthe CCompiler

Low-Level CLanguageParameter Passing

CompilerOptimizations

Bitwise Operators

Bit Fields

Review:Layers ofAbstraction

Layers of Abstraction

After CMPUT 114, 115, 201, 229, you have now seen manylayers of abstraction.

1 Special-purpose and scripting languages (e.g., draw)2 High-level programming languages (e.g., C and Java)3 Libraries and packages (e.g., Standard I/O, Swing)4 Run-Time System / Operating System (e.g., Linux,

JVM, Windows)5 Assembly language6 Hardware: CPU, memory bus, I/O

CMPUT 379 will expand on operating systems.CMPUT 329, 429 will expand on computer architecture andhardware.CMPUT 415, 425 will expand on compilers andprogramming languages.

Page 172: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Outline

Part VI

C++ and OO Concepts

13 C++

14 Generic Programming

15 C++ Standard Template Library

Page 173: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction

Developed by Bjarne Stroustrup at AT&T Bell Labs inthe early 1980sBut, as with Java, Smalltalk and others, the originalobject-oriented concepts have roots in Simula67.Originally, it was known as "C with Classes"Since the early days, many people have contributed tostandardizing and developing the languageToday, C++ is a powerful, object-oriented,general-purpose programming language.

Page 174: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (2)

C++ is an object-oriented (OO) language because itsupports:

1 Encapsulation: As with Java, classes in C++ are away to closely couple data (i.e., data members) andcode (i.e., methods or member functions). But, C++has multiple inheritance of code and data.

2 Inheritance: As with Java, C++ allows for classderivation (aka subclassing, aka specialization) andsubstitution (i.e., using an object of a subclass in placeof an object of a superclass)

3 Polymorphism: As with Java, C++’s virtual functionscan select the appropriate method depending on therun-time type of the object.

Page 175: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (3)

Furthermore, C++ has modern, powerful features such as:

1 Exception handling, like Java.2 Templates for generic programming. Java is starting to

gain generics.3 The Standard Template Library, now just part of the

standard C++ library.4 Multiple inheritance.

Page 176: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (4)

But, C++ has some drawbacks:1 C++ is a big language. That’s good and bad.2 It is easy to mis-use some C++ mechanisms (e.g.,

operator overloading).3 Some of C++’s high-level abstractions hide too many

performance overheads.1 constructors hide the overheads of local

variables/objects2 inheritance hides the storage overheads of objects3 multiple inheritance hides the overheads of method

dispatch4 operator overloading hides the cost of creating and

using an object

Many of these drawbacks are not really C++’s fault. But, theprogrammer (and class designer) has greater responsibilityto design and document well.

Page 177: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (5)

Some very personal, subjective recommendations:

1 Do NOT use operator overloading until you haveprogrammed in C++ for 2 or 3 years.

2 Since C++ gives you a choice, do NOT make a methodpolymorphic until you are sure that you need it.

Many people would disagree with me.But, I am a systems person who uses OO. I am not anOO person who wants to write systems software.In the future, I hope this can be handled with compileroptimizations.

3 Do NOT use multiple inheritance unless you absolutelymust do so.

Page 178: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Encapsulation: Classes

See King, pg. 428paullu@ug30:~/C201>cat t27.C#include <iostream>using namespace std;

class ClassA{

private:int dataMem;

public:int dataMem2;ClassA() { dataMem = 1; } // CtorClassA( int i ) { dataMem = i; }// Ctor~ClassA(){}; // Dtorint getNum() { return dataMem; }

};

int main( int argc, char ** argv ){

ClassA anA;ClassA anotherA( 2 );

cout << "Hello world " << anA.getNum();cout << " " << anotherA.getNum() << endl;

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi t27.Cpaullu@ug30:~/C201>./a.outHello world 1 2

Use g++ to compile .CfilesClasses are used toinstantiate objectsEncapsulation couplesdata members andmember functionsC++ classes look a lotlike C structures. In fact,in C++, structures canhave member functions.

Page 179: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Encapsulation: Classes (2)

paullu@ug30:~/C201>cat t27.C#include <iostream>using namespace std;

class ClassA{

private:int dataMem;

public:int dataMem2;ClassA() { dataMem = 1; } // CtorClassA( int i ) { dataMem = i; }// Ctor~ClassA(){}; // Dtorint getNum() { return dataMem; }

};

int main( int argc, char ** argv ){

ClassA anA;ClassA anotherA( 2 );

cout << "Hello world " << anA.getNum();cout << " " << anotherA.getNum() << endl;

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi t27.Cpaullu@ug30:~/C201>./a.outHello world 1 2

Pure C++ programs usedifferent header files(e.g., <iostream>)C++ namespaces are amodern feature to allowname and identifieroverloadingusing namespacestd; simplypre-declares all thenames in the stdnamespace. It is acommonly used idiom.

Page 180: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Encapsulation: Classes (3)

paullu@ug30:~/C201>cat t27.C#include <iostream>using namespace std;

class ClassA{

private:int dataMem;

public:int dataMem2;ClassA() { dataMem = 1; } // CtorClassA( int i ) { dataMem = i; }// Ctor~ClassA(){}; // Dtorint getNum() { return dataMem; }

};

int main( int argc, char ** argv ){

ClassA anA;ClassA anotherA( 2 );

cout << "Hello world " << anA.getNum();cout << " " << anotherA.getNum() << endl;

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi t27.Cpaullu@ug30:~/C201>./a.outHello world 1 2

Classes can havepublic, private, andprotected members.Compare with Java’sverbose use of thekeywords.C++ has constructors(like Java) anddestructors (unlikeJava!).C++ supports separatecompilation of classes(coming up) and well asJava-like in-line definitionof methods.

Page 181: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Encapsulation: Classes (4)

paullu@ug30:~/C201>cat t27.C#include <iostream>using namespace std;

class ClassA{

private:int dataMem;

public:int dataMem2;ClassA() { dataMem = 1; } // CtorClassA( int i ) { dataMem = i; }// Ctor~ClassA(){}; // Dtorint getNum() { return dataMem; }

};

int main( int argc, char ** argv ){

ClassA anA;ClassA anotherA( 2 );

cout << "Hello world " << anA.getNum();cout << " " << anotherA.getNum() << endl;

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi t27.Cpaullu@ug30:~/C201>./a.outHello world 1 2

Instead of printf(),C++ has cout fromiostream.Instead of scanf(),C++ has cin fromiostream (not shownhere).But, you can still useprintf() (not shownhere) if you wish.Stroustrup would be veryunhappy about that.

Page 182: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Encapsulation: Classes (5)

paullu@ug30:~/C201>ls t28*t28.C t28.H t28.main.C

paullu@ug30:~/C201>cat t28.Hclass ClassA{

private:int dataMem;

public:int dataMem2;ClassA();ClassA( int i );~ClassA();int getNum();

};

paullu@ug30:~/C201>cat t28.C#include "t28.H"

ClassA::ClassA() { dataMem = 1; }ClassA::ClassA( int i ) { dataMem = i; }ClassA::~ClassA() { }int ClassA::getNum() { return dataMem; }

paullu@ug30:~/C201>cat t28.main.C#include <iostream>using namespace std;

#include "t28.H"

int main( int argc, char ** argv ){

ClassA anA;ClassA anotherA( 2 );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi t28.C t28.main.C

Separate compilation,the preprocessor, andprintf() arecarry-overs from C.

Page 183: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Inheritance

paullu@ug30:~/C201>cat t29.C#include <stdio.h>class ClassA{

private:int dataMem;

public:ClassA( int i ) { dataMem = i; }int getNum() { return dataMem; }

};

class ClassB : public ClassA{

private:int dataMem;

public:ClassB() : ClassA( 3 ) { };

};

int main( int argc, char ** argv ){

ClassA anA( 1 );ClassB anB;

printf( "%d %d\n",anA.getNum(), anB.getNum() );

printf( "%d %d\n",sizeof( anA ), sizeof( anB ) );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi t29.C

paullu@ug30:~/C201>./a.out1 34 8

Class B can extendClass A throughinheritance.The new Class B has allof the data members andmember functions ofClass A

Page 184: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Inheritance (2)

paullu@ug30:~/C201>cat t30.C#include <stdio.h>

class ClassA{

private:int dataMem;

public:ClassA( int i ) { dataMem = i; }int getNum() { return dataMem; }

};

class ClassB : public ClassA{

private:int dataMem;

public:ClassB() : ClassA( 3 ) { };int getNum( int i ) { return i; }int getNum() { return -1; }

};

int main( int argc, char ** argv ){

ClassA anA( 1 );ClassB anB;

printf( "%d %d %d\n",anA.getNum(), anB.getNum(),anB.getNum( 4 ) );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi t30.C

paullu@ug30:~/C201>./a.out1 -1 4

Function overloading:different implementationswith the same name butdifferent arguments (e.g.,different type)Function overriding:replace theimplementation in thesuper/parent class with anew implementation inthe child class

Page 185: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Polymorphism

paullu@ug30:~/C201>cat t31.C#include <stdio.h>

class ClassA{

private:int dataA;

public:char * get() { return "Class A"; }

};

class ClassB : public ClassA{

private:int dataB;public:

char * get() { return "Class B"; }};

void sub1( ClassA * anAPtr ){

printf( "%s\n", anAPtr->get() );} /* sub */

void sub2( ClassB * anBPtr ){

printf( "%s\n", anBPtr->get() );} /* sub */

int main( int argc, char ** argv ){

ClassA anA;ClassB anB;

sub1( &anA );sub1( &anB );sub2( &anB );

} /* main */paullu@ug30:~/C201>make t31g++ -Wall -ansi t31.Cpaullu@ug30:~/C201>./a.outClass AClass AClass B

Substitutability: BecauseanB is-a object of ClassA (as well), we can callsub1() with &anB

Page 186: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Polymorphism (2)

paullu@ug30:~/C201>cat t32.C#include <stdio.h>

class ClassA{

private:int dataA;

public:virtual char * get()

{ return "Class A"; }};

class ClassB : public ClassA{

private:int dataB;

public:char * get() { return "Class B"; }

};

void sub1( ClassA * anAPtr ){

printf( "%s\n", anAPtr->get() );} /* sub */

void sub2( ClassB * anBPtr ){

printf( "%s\n", anBPtr->get() );} /* sub */

int main( int argc, char ** argv ){

ClassA anA;ClassB anB;

sub1( &anA );sub1( &anB );sub2( &anB );

} /* main */paullu@ug30:~/C201>make t32g++ -Wall -ansi t32.Cpaullu@ug30:~/C201>./a.outClass AClass BClass B

Call siteanAPtr->get() insub1() is nowpolymorphic due tovirtual functionget() in Class A.

Page 187: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Polymorphism (3)

paullu@ug30:~/C201>cat t33.C#include <stdio.h>

class ClassA{

private:int dataA;

public:virtual char * get() { return "Class A"; }

};

class ClassB : public ClassA{

private:int dataB;

public:char * get() { return "Class B"; }

};

int main( int argc, char ** argv ){

ClassA anA;ClassB anB;

printf( "%d %d\n", sizeof( anA ), sizeof( anB ) );} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi t33.Cpaullu@ug30:~/C201>./a.out8 12

The C++ Memory Model:objects with polymorphic(aka virtual) memberfunctions have “hidden”storage overheads for apointer to a virtualfunction table

Page 188: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Thinking in C++

What you learned in CMPUT 114/115 about Java and OOdesign is very important in using C++. For example:

1 Keep your methods small and clear in theirbehaviour/purpose. In C++, you also have the (easy)option to use functions too.

2 Use inheritance to model the is-a relationship only. Usesubstitutability as the “acid test” for this decision.

3 When appropriate, use object composition to model thehas-a relationship.

4 Avoid making data members public (or evenprotected). Use accessor methods wheneverpossible.

Page 189: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Thinking in C++ (2)

5 Remember that C++ does NOT have garbagecollection. But, you can find a number of differentlibraries to implement garbage collection.

6 C++ is a big topic. Object-oriented design is a big topic.Nobody can truly master them without sufficientexperience. But, you can master both.

Page 190: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Allocation/Deallocation

Object allocation and deallocation in C++ are handledby new and delete, instead of malloc() andfree(). Why?Memory allocation and deallocation can still be handledwith malloc() and free().In combination with constructors and destructors,allocation and deallocation can be handled in lesserror-prone ways than in C.Overheads vs. C: The cost of object creation anddestruction is not as predictable as in C.

Page 191: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Allocation/Deallocation (2)

Using pseudo-code:class MatrixList{

private:RowList * head;

public:MatrixList() { head = NULL; }~MatrixList() { /* For each RowList, delete */ }void add( /* params */ );RowList * find( /* params */ );

};

The constructor is the logical place to put initializations:1 Setting data members to NULL2 memset()ing buffers to zero3 Setting counters to zero (e.g., reference counting)4 Acquiring a lock (see Java’s synchronized methods and

CMPUT 379)NOTE: Constructors are invoked either when the objectgoes into scope, or new is called.

Page 192: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Allocation/Deallocation (3)

class MatrixList{

private:RowList * head;

public:MatrixList() { head = NULL; }~MatrixList() { /* For each RowList, delete */ }void add( /* params */ );RowList * find( /* params */ );

};

The destructor is the logical place to put finalizations:1 Deallocating (e.g., delete or free) composite objects

(e.g., has-a relationship)2 Decrementing counters (in another object??) to zero

(e.g., reference counting)3 Flushing a buffer4 Freeing up a lock (see Java’s synchronized methods

and CMPUT 379)NOTE: Destructors are invoked either when the object goesout of scope, or delete is called.

Page 193: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Allocation/Deallocation (4)

Using pseudo-code:

class MatrixList{

private:RowList * head;

public:MatrixList() { head = NULL; }~MatrixList(){ /* For each RowList, delete */ }void add( Row newRow ){

RowList * newNode;newNode = new RowList;/* insert into list*/

}RowList * find( /* params */ );

};

As part of new, the appropriate constructor(s) forRowList are invoked.

Page 194: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Allocation/Deallocation (5)

Using pseudo-code:class MatrixList{

private:RowList * head;

public:MatrixList() { head = NULL; }~MatrixList(){ /* For each RowList, delete */

RowList * oldNode;/* for each node, walk the list */{

delete oldNode;oldNode = NULL; /* Best practice */

}}void add( Row newRow ){

RowList * newNode;newNode = new RowList;/* insert into list*/

}RowList * find( /* params */ );

};

As part of delete, the appropriate destructor(s) forRowList are invoked.

Page 195: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction

Re-using code is a long-standing goal of softwareengineering. Some of our options include:

1 Libraries (e.g., Standard I/O in C)2 Unix component model (re-use of executables)3 Open source: Lexical copying or cloning of code4 New: Generic programming

Often, a function or method is “exactly” what we want,except that it operates on the “wrong” type.For example, code to implement a stack of integers, butnot a stack of doubles. Or, a linked list of matrices, butnot a linked list of matrix rows.Pushing/popping items on a stack (basically) onlydepends on the ability to copy/assign the data type.Adding, removing, and finding items in a linked list onlydepends on the ability to follow pointers andcopying/assigning of data.

Page 196: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (2)

Perhaps we can have the compiler do the hard work?Perhaps we can have generic containers for (nearly)arbitrary data?Generic algorithms: Implementations of algorithms thatare valid for any data type (aka abstract data type) thatmeet certain behaviour criteria:

1 Do we know how to copy the object?2 Do we know how to compare the object?3 Do we know how to iterate among a collection?4 Do we know how to index or search within a collection?

For all of the built-in types (e.g., int, char), theanswer is yes.

Page 197: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates

The main C++ language mechanism for supportinggeneric programming is the template. There are:

1 Class templates2 Function templates

In combination with clever uses of objects andtemplates (i.e., policy), the Standard Template Library(STL) provides a library of generic containers,algorithms, and iterators.Note the difference between mechanism (e.g., can I dosomething) and policy (e.g., what shall I do with it andhow).C’s qsort() was the closest thing to genericprogramming.C++’s templates are a compile-time mechanism.

Page 198: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (2)

paullu@ug30:~/C201>cat t34.C#include <stdio.h>#include <vector>using namespace std;

int main( int argc, char ** argv ){

vector< int > v( 10 );

v[ 0 ] = 1;v[ 1 ] = 2;v[ 2 ] = 3;v.push_back( 4 );

printf( "%d %d %d\n", v[ 0 ], v[ 10 ],v.size() );

{ /* New scope */vector< double > v( 5 );

v[ 0 ] = 1.1;v[ 1 ] = 2.2;v[ 2 ] = 3.3;v.push_back( 4.4 );

printf( "%g %g %d\n", v[ 0 ], v[ 5 ],v.size() );

} /* inner v is dtor’ed here */} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi t34.C

paullu@ug30:~/C201>./a.out1 4 111.1 4.4 6

vector<> is a classtemplateIt can be used almostlike a C arrayIt supports otherfunctionality: push(automatically grows),pop, insert, etc.

Page 199: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (3)

paullu@ug30:~/C201>cat t35.C#include <stdio.h>#include <vector>using namespace std;

/* Example only. B is-a vector<int> ? */class B : public vector< int >{

public:B() : vector< int >( 10 ) { }void hello(){

printf( "Hello\n" );} /* hello */

}; /* B */

int main( int argc, char ** argv ){

B v;

v[ 0 ] = 1;v[ 1 ] = 2;v[ 2 ] = 3;v.push_back( 4 );

printf( "%d %d %d\n", v[ 0 ], v[ 10 ], v.size() );v.hello();

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi -g t35.C

paullu@ug30:~/C201>./a.out1 4 11Hello

Like any class,vector<int> can beused as a superclassBut, is B really avector<int>?

Page 200: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (4)

paullu@ug30:~/C201>cat t36.C#include <stdio.h>#include <vector>using namespace std;

/* B has-a vector<int> */class B{

private:vector< int > myV;

public:B() : myV( 10 ) { }void put( int index, int val ){

myV[ index ] = val;} /* put */int get( int index ){

return myV[ index ];} /* get */void push_back( int val ){

myV.push_back( val );} /* push_back */int size(){

return myV.size();} /* size */

}; /* B */

int main( int argc, char ** argv ){

B v;

v.put( 0 , 1 );v.put( 1 , 2 );v.put( 2 , 3 );v.push_back( 4 );

printf( "%d %d %d\n",v.get( 0 ), v.get( 10 ), v.size() );

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi -g t36.Cpaullu@ug30:~/C201>./a.out1 4 11

Here, B has-avector<int>

B also provides wrappermethods to redirectsome methods tovector<int>

Page 201: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (5)

int main( int argc, char ** argv ){

B v;

v.put( 0 , 1 );v.put( 1 , 2 );v.put( 2 , 3 );v.push_back( 4 );

printf( "%d %d %d\n",v.get( 0 ), v.get( 10 ), v.size() );

} /* main */

could look like...

int main( int argc, char ** argv ){

B v;

v[ 0 ] = 1;v[ 1 ] = 2;v[ 2 ] = 3;v.push_back( 4 );

printf( "%d %d %d\n", v[ 0 ], v[ 10 ], v.size() );} /* main */

...if we used operatoroverloadingBut, B has-avector<int>. B is nota vector<int>.Therefore, why make B’soperators substitutablefor vector<int>’soperators?There might be a goodreason, but...

Page 202: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (6)

(Some formatting changes made below.)

paullu@ug30:~/C201>gdb a.outGNU gdb 6.3Copyright 2004 Free Software Foundation, Inc.GDB is free software, covered by the GNU General Public License, and you arewelcome to change it and/or distribute copies of it under certain conditions.Type "show copying" to see the conditions.There is absolutely no warranty for GDB. Type "show warranty" for details.This GDB was configured as "i486-slackware-linux"...Using host libthread_db library "/lib/libthread_db.so.1".

(gdb) br 39Breakpoint 1 at 0x804862e: file t36.C, line 39.

(gdb) runStarting program: /home/dsk05/prof/paullu/C201/a.out

Breakpoint 1, main (argc=1, argv=0xbffffab4) at t36.C:3939 printf( "%d %d %d\n",

(gdb) info localv = {

myV = {<std::_Vector_base<int, std::allocator<int> >> ={<std::_Vector_alloc_base<int, std::allocator<int>, true>> ={_M_start = 0x804a9d0,

_M_finish = 0x804a9fc,_M_end_of_storage = 0x804aa20}, <No data fields>},

<No data fields>}}

Page 203: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (7)

(gdb) info stack#0 main (argc=1, argv=0xbffffab4) at t36.C:39(gdb) ptype vtype = class B {private:

std::vector<int, std::allocator<int> > myV;

public:B(void);void put(int, int);int get(int);void push_back(int);int size();

}(gdb) printf "%d\n", v.get(0)1(gdb) printf "%d\n", v.get(1)2(gdb) printf "%d\n", v.get(2)3(gdb) printf "%d\n", v.get(3)0(gdb) printf "%d\n", v.size()11

Notice how myV in B as been instantiated (atcompile-time) as a std::vector<int,std::allocator<int> >

Page 204: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (8)

paullu@ug30:~/C201>cat t37.C#include <stdio.h>#include <vector>using namespace std;

/* B has-a vector<BaseType> */template< typename BaseType > class B{

private:vector< BaseType > myV;

public:B< BaseType >() : myV( 10 ) { }void put( int index, BaseType val ){

myV[ index ] = val;} /* put */BaseType get( int index ){

return myV[ index ];} /* get */void push_back( BaseType val ){

myV.push_back( val );} /* push_back */int size(){

return myV.size();} /* size */

}; /* B<> */

int main( int argc, char ** argv ){

B< int > v;B< float > vf;

v.put( 0 , 1 );v.put( 1 , 2 );v.put( 2 , 3 );v.push_back( 4 );

printf( "%d %d %d\n",v.get( 0 ), v.get( 10 ), v.size() );

vf.put( 0, 1.1 );printf( "%g\n", vf.get( 0 ) );

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi -g t37.Cpaullu@ug30:~/C201>./a.out1 4 111.1

We can write B as ourown class template

Page 205: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (9)

paullu@ug30:~/C201>cat t38.CHeader, Class template for B, as before

/* B<BaseType> & obj is a ref arg */template< typename BaseType >void setVal( B<BaseType> & obj, int index,

BaseType val, char * name ){

static char * remName = NULL;if( remName == NULL )

remName = name;

obj.put( index, val );printf( "Inside %s (%p)\n", remName, remName );

} /* setVal<>() */

int main( int argc, char ** argv ){

B< int > v;B< float > vf;

v.put( 0 , 1 );setVal( v, 0, (int)1, "setVal<int>" );setVal( v, 1, (int)2, "garbage" );setVal( v, 2, (int)3, "garbage" );printf( "%d %d\n",

v.get( 0 ), v.get( 1 ) );setVal( vf, 0, (float)1.1, "setVal<float>" );setVal( vf, 1, (float)2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi -g t38.Cpaullu@ug30:~/C201>./a.outInside setVal<int> (0x8049034)Inside setVal<int> (0x8049034)Inside setVal<int> (0x8049034)1 2Inside setVal<float> (0x804904f)Inside setVal<float> (0x804904f)1.1 2.2

Function templatesNote that, like structs,objects in C++ arepassed by value.Note the referenceargument (& obj)Note that there are twofunctions(setval<int>() andsetval<float>())

Page 206: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (10)

/* B<BaseType> & obj is a ref arg */template< typename BaseType >void setVal( B<BaseType> & obj, int index,

BaseType val, char * name ){

static char * remName = NULL;if( remName == NULL )

remName = name;

obj.put( index, val );printf( "Inside %s (%p)\n", remName, remName );

} /* setVal<>() */

int main( int argc, char ** argv ){

B< int > v;B< float > vf;

v.put( 0 , 1 );setVal( v, 0, 1, "setVal<int>" );setVal( v, 1, 2, "garbage" );setVal( v, 2, 3, "garbage" );printf( "%d %d\n",

v.get( 0 ), v.get( 1 ) );setVal( vf, 0, 1.1, "setVal<float>" );setVal( vf, 1, 2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi -g t39.Ct39.C: In function ‘int main(int, char**)’:t39.C:50: error: no matching function for

call to ‘setVal(B<float>&, int, double,const char[14])’

t39.C:51: error: no matching function forcall to ‘setVal(B<float>&, int, double,const char[8])’

make: *** [t39] Error 1

Templates can causecryptic, nested errormessages.The programmer has tolearn a lot of instantiationand matching rules. It isworth it, but tricky!What’s wrong here?

Page 207: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (11)

We changed from:setVal( vf, 0, (float)1.1, "setVal<float>" );setVal( vf, 1, (float)2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

to:setVal( vf, 0, 1.1, "setVal<float>" );setVal( vf, 1, 2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

and got:paullu@ug30:~/C201>makeg++ -Wall -ansi -g t39.Ct39.C: In function ‘int main(int, char**)’:t39.C:50: error: no matching function for call to ‘setVal(B<float>&, int,

double, const char[14])’t39.C:51: error: no matching function for call to ‘setVal(B<float>&, int,

double, const char[8])’make: *** [t39] Error 1

By default, the compiler interprets 1.1 and 2.2 asdouble constants, not float

Page 208: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (12)

We could also go from:

setVal( vf, 0, (float)1.1, "setVal<float>" );setVal( vf, 1, (float)2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

to:

setVal<float>( vf, 0, 1.1, "setVal<float>" );setVal<float>( vf, 1, 2.2, "garbage" );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

In C++, there are a variety of mechanisms to explicitlyforce the compiler to select a particular template (e.g.,setVal<float>), class/type (e.g., (float)2.2).Be warned of these kinds of type-based issues forfunction overloading (compile-time) and polymorphism(run-time).

Page 209: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (13)

pullu@ug30:~/C201>cat t41.C#include <stdio.h>#include <vector>using namespace std;

/* B has-a vector<BaseType> */template< typename BaseType > class B{

private:vector< BaseType > myV;

public:B< BaseType >() : myV( 10 ) { }void put( int index, BaseType val ){

myV[ index ] = val;} /* put */BaseType get( int index ){

return myV[ index ];} /* get *//* Some methods omitted */

}; /* B<> */

/* cont is a template template parameter */template< typename BaseType,

template <typename BaseType> class cont >void setVal( cont< BaseType > & obj,

int index, BaseType val ){

obj.put( index, val );} /* setVal<>() */

int main( int argc, char ** argv ){

B< int > v;B< float > vf;

setVal( v, 0, 1 );setVal( v, 1, 2 );setVal( v, 2, 3 );

printf( "%d %d\n",v.get( 0 ), v.get( 1 ) );

setVal( vf, 0, (float)1.1 );setVal( vf, 1, (float)2.2 );printf( "%g %g\n", vf.get( 0 ), vf.get( 1 ) );

} /* main */paullu@ug30:~/C201>makeg++ -Wall -ansi -g t41.C

paullu@ug30:~/C201>./a.out1 21.1 2.2

Templates can beparameters to othertemplates!

Page 210: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Templates (14)

With templates instantiating other templates, it is easyto have syntax (or other) errors cause dozens of linesof compile-time error messages.Compilers are getting better, but it will remaincomplicated!But, the abstraction power of templates is worth it.

Page 211: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction

Templates allow C++ to work generically, regardless ofbase types.If we add some other concepts, we have the basis ofthe Standard Template Library (STL), which is now justpart of the C++ Standard LibrayThe main concepts are:

1 Containers: vectors, lists, queues, stacks, maps, sets,bitsets

2 Iterators: forward, bidirectional, random accessIntuition: generalized pointers

3 Algorithms: search, sort4 Time complexity: For example, inserting into a vector,

without growing it, is constant (i.e., O(1)) time.Other guarantees for “adding element with growing”,“removal of first element”, “removal of middle element”,“test for existing of key”

Page 212: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Introduction (2)

Although templates allow for specification of an“arbitrary” base type during instantiation atcompile-time, there are still some constraints:

1 Containers and Iterators: iterators need a way to accessa specific element in the container (e.g., indexing)

2 Iterators and Algorithms: some algorithms requirerandom access

Page 213: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Vectors (again)

paullu@ug30:~/C201>cat t42.C#include <stdio.h>#include <vector>using namespace std;

int main( int argc, char ** argv ){

vector< int > v( 3 );vector< float > vf( 5 );vector< int >::iterator itrv;vector< float >::iterator itrvf;

int i = 4;for( itrv = v.begin();

itrv != v.end(); itrv++ ){

*itrv = i++;}for( itrv = v.begin();

itrv != v.end(); itrv++ ){

printf( "%d ", *itrv );}printf( "\n" );

i = 2;for( itrvf = vf.begin();

itrvf != vf.end(); itrvf++ ){

*itrvf = (i++) + 0.2;}

for( itrvf = vf.begin();itrvf != vf.end(); itrvf++ )

{printf( "%g ", *itrvf );

}printf( "\n" );

} /* main */

paullu@ug30:~/C201>makeg++ -Wall -ansi -g t42.Cpaullu@ug30:~/C201>./a.out4 5 62.2 3.2 4.2 5.2 6.2

Page 214: Computing Science (CMPUT) 201ugweb.cs.ualberta.ca/~c201/F07/schedule/lectures/c201.slides.draft.… · CMPUT 201 Key Points Preparing for Labs Overview Key Points Keep in mind: 1

CMPUT 201

C++Introduction

Encapsulation

Inheritance

Polymorphism

Thinking in C++

Allocation/Deallocation

GenericProgrammingIntroduction

Templates

C++ StandardTemplateLibraryIntroduction

Vectors (again)

Algorithms

Algorithms

Some of the STL algorithms include:1 sort()2 find()3 reverse()4 for_each()