Introduction to C and Unix - PowerPoint PPT Presentation

1 / 69
About This Presentation
Title:

Introduction to C and Unix

Description:

SSH room 502: catwoman, robin, obelix, cesar, asterix, ... install Cygwin with Devel package (www.cygwin.com) Test your assignments on a SUN workstation! ... – PowerPoint PPT presentation

Number of Views:31
Avg rating:3.0/5.0
Slides: 70
Provided by: rn3
Category:

less

Transcript and Presenter's Notes

Title: Introduction to C and Unix


1
Introduction to C and Unix
  • Vincent Levesque
  • vleves_at_cim.mcgill.ca
  • Based on Prof. Cooperstocks
  • Crash Course in C
  • http//www.cim.mcgill.ca/jer/courses/C/

2
UNIX in ECE dept.
  • SUN workstations
  • SSH room 502 catwoman, robin, obelix, cesar,
    asterix, idefix, falbala, getafix
  • SSH only bruce, penguin, thor, wendee, wayne
  • e.g catwoman.ece.mcgill.ca
  • Windows PC
  • connect to any workstation using SSH
  • see instructions on course web page
  • http//www.cim.mcgill.ca/sinclair/Ian20Sinclair_
    files/courses/os/OS20Course20Home20Page.htm

3
UNIX at Home
  • Options
  • SSH (putty, Cygwin, etc.)
  • install Linux
  • install Cygwin with Devel package
    (www.cygwin.com)
  • Test your assignments on a SUN workstation!

4
Entering commands
  • enter commands on the shells command prompt
  • similar to DOS

5
Getting Help
  • Manual pages
  • man printf
  • man 3 printf
  • man k print
  • Info
  • info printf
  • Other
  • search on the web and in newsgroups (google)
  • numerous books

6
Filesystem Navigation
  • Wildcards
  • (any group of characters), ? (a single
    character)
  • Basic Commands

7
Redirection and Pipes
  • Redirection
  • sends output of a command to a file
  • gt Creates or overwrites a file
  • ls gt listing.txt
  • gtgt Appends to a file
  • prog gtgt log.txt
  • Pipe
  • sends output of a command to the input of another
    command
  • cat readme.txt more

8
Viewing and Editing Files
  • Viewing
  • cat displays the content of a file
  • cat readme.txt
  • cat readme.txt more
  • Editing
  • many text editors are available
  • emacs
  • vi
  • pico
  • etc.

9
File Permissions
  • -rwxr-xr--
  • 3 user classes
  • owner
  • group
  • world
  • 3 permission types
  • r (read)
  • w (write)
  • x (execute)
  • use ls -l to see file permissions
  • ls l foo.txt
  • -rw-r-xr-x foo.txt

10
File Permissions (2)
  • use chmod to change file permissions
  • (owner gt u, group gt g, world gt o)
  • chmod o-rx foo.txt
  • ls l foo.txt
  • -rw-r-x--- foo.txt
  • chmod gw foo.txt
  • ls l foo.txt
  • -rw-rwx--- foo.txt
  • use a private directory for your course work
  • mkdir private
  • chmod 700 private
  • ls ld private
  • drwx------ private

11
Compiling
  • Steps to a running program
  • vi prog.c
  • gcc prog.c
  • ./a.out

source code
object code
compiler
input data
executable object code
output data
12
Separate Compilation
  • gcc -c part1.c
  • gcc -c part2.c
  • gcc part1.o part2.o
  • a.out

part1.o
part1.c
preprocess -gt translate
part2.c
part2.o
preprocess -gt translate
part1.o part2.o
a.out
link
13
Makefiles
  • Example
  • Sample Makefile
  • pgm prog.o sub.o
  • gcc -o pgm prog.o sub.o
  • prog.o incl.h prog.c
  • gcc -c prog.c
  • sub.o incl.h sub.c
  • gcc -c sub.c
  • Use make command to execute the Makefile
  • make pgm
  • make
  • Note
  • A tab character is required before gcc!
  • http//www.cim.mcgill.ca/jer/courses/os/help/make
    files.html

14
Running your Program
  • any file can be executed (remember file
    permissions!)
  • no special extension such as .exe in dos
  • you might need to specify the full path
  • ./prog

15
Your First C Program
  • "The only way to learn a new programming language
    is by writing programs in it" KR
  • begin hello.c
  • ---------------
  • / A simple program that prints something /
  • include ltstdio.hgt
  • / main() is the entry point of any C program
    /
  • main ()
  • printf ("Hello, world!\n")
  • ---------------
  • end hello.c

16
Declarations
  • Example
  • float x
  • double d 5
  • int p, i, a100
  • char s21
  • Syntax
  • type variable_name, ... value
  • Rules
  • declarations must precede executable statements
  • int type may be modified by long, short,
    unsigned

17
Changing Variable Values
  • Example
  • int x, y, z
  • x 2
  • x x 1
  • Getting Fancy
  • y z 4 5
  • x 1
  • x
  • y x--
  • y x
  • Note
  • assignment statements return value, which may or
    may not be ignored same goes for increment
    statements

18
Formatted Output
  • Example
  • int i 10
  • float f 2.5
  • char s "hi"
  • printf ("Jack\'s integer is d\n", i)
  • printf ("Jill\0x27s float is f\n", f)
  • printf ("My string s s\n", s)
  • Syntax
  • printf (string_with_formatting, var1, var2, ...)
  • Formats d integer, f float, c character, s
    string,
  • Note "escape sequences" \n newline, \' quote,
    \0x27, etc.
  • include ltstdio.hgt is compulsory more about it
    later

19
Formatted Input
  • Example
  • include ltstdio.hgt
  • int i
  • float f
  • scanf ("d f\n", i, f)
  • / inputs an integer and a float /
  • Syntax
  • scanf (string_with_formatting, var1, var2,...)
  • Note
  • The ampersand () is necessary because scanf
    modifies the values stored in the respective
    variables by comparison, printf only uses the
    values, without modifying them. More about this
    later

20
I/O Example
  • include ltstdio.hgt
  • main ()
  • int n
  • float x
  • char mark
  • scanf ("d f c", n, x, mark)
  • printf ("Of d s,\nf got c\s\n",
  • n, "students", x, mark)
  • Input
  • 86 85.999 A
  • Output
  • Of 86 students,
  • 85.999001 got A's

21
Conditional Statements
  • Example
  • if (age lt 0)
  • printf ("warning negative age\n")
  • age -age
  • Syntax
  • if (condition) statement
  • if (condition) statement else statement
  • Rules
  • the condition is an int ! (no booleans)
  • parentheses required around conditional
    expression
  • use curly braces to make a compound statement

22
More Conditionals
  • Example
  • if (x lt 0)
  • printf ("x is less than 0\n")
  • else if (x 0)
  • printf ("x is equal to 0\n")
  • else
  • printf ("x is greater than 0\n")
  • Whats wrong with this?
  • if (x lt 0)
  • if (y lt z)
  • printf ("y is less than z\n")
  • else
  • printf ("x not less than 0\n")

23
While Loops
  • Example
  • / print "hi" forever /
  • while (1)
  • printf ("hi")
  • Syntax
  • while (condition)
  • statement
  • Rules (again)
  • the condition is an int ! (no booleans)
  • parentheses required around conditional
    expression
  • use curly braces to make a compound statement

24
For Loops
  • Example
  • / print "hi" three times /
  • int i / i continues to exist when loop ends /
  • for (i 0 i lt 3 i)
  • printf ("hi")
  • Syntax
  • for (statement1 condition statement2)
  • statement3
  • Equivalent to
  • statement1
  • while (condition)
  • statement3
  • statement2

25
Loop Example
  • / print squares up to 100 /
  • main ( )
  • int i
  • for (i 0 i lt 10 i)
  • printf ("d \n", i i)
  • Note
  • cant do for (int i 0 ...

26
Arrays
  • int years45
  • float temperatures 11
  • void main ()
  • years0 2000
  • temperatures11 -45.67 / illegal /
  • Rules
  • indices start at zero
  • maximum valid index is the size of the array
    minus 1
  • but C lets you go beyond the declared boundaries
  • temperatures11 is illegal

27
Characters
  • Characters
  • char a, b, c1, c2
  • a '0' b '\037' c1 'K' c2 c1 1
  • Assigns values 48, 31, 75, 76
  • The sequences '0',...,'9', 'a',...,'z',
    'A',...,'Z' contain characters numbered
    consecutively
  • Casting
  • printf ("c d\n", c1, (int) c1)
  • Outputs K 75

28
Strings
  • Strings are '\0'-terminated arrays of char
  • char s3 "hi" / invisible '\0' /
  • char t3 'h', 'i', '\0'
  • char s "hi"
  • String operations
  • include ltstring.hgt
  • strlen ("there") / returns 5 /
  • strcpy (s, t) / copy t to s /
  • strcmp (s, t) / alphabetical comparison /

29
Functions
  • / Increment takes an integer argument and
  • returns the argument plus one.
  • /
  • int incr (int i)
  • int j
  • j i 1
  • return j
  • main ()
  • int k, m 4
  • k incr(m)
  • printf ("k d, m d\n", k, m)
  • output k 5, m 4

30
More about Functions
  • might have no return type, and no return
    statement
  • void printhi ()
  • printf ("hi\n")
  • parameters are copied and can be modified
  • int incr (int i)
  • i
  • return i

31
Variables within Functions
  • But this does not work
  • void no_incr (int i)
  • i
  • void main ()
  • int x 5
  • no_incr(x)
  • printf ("d\n", x)
  • beware that modifications are on internal copies
    of the parameters.
  • note void main() since main does not return a
    value

32
C Preprocessor Directives
  • Operations before compilation phase
  • include "header" files that contain pre-supplied
    functions
  • include ltstring.hgt
  • this line will be substituted by the contents of
    the file
  • define symbolic constants
  • define MY_LARGE_NUMBER 12345
  • define MY_NIFTY_STRING abc
  • what happens if you add a by mistake?
  • define MY_LARGE_NUMBER 12345
  • int x MY_LARGE_NUMBER 1
  • gt int x 1235 1 / error! /

33
Header Files
  • / File myheader.h
  • Definitions for program build.c
  • /
  • / Booleans /
  • typedef int boolean_t
  • define TRUE 1
  • define FALSE 0
  • / node type /
  • typedef struct node_t
  • ...
  • / function prototypes /
  • node_t NewNode(char label, int cost)
  • void KillNode (node_t node)

34
Make your own booleans
  • C has boolean operations on int
  • ! !
  • However, C has no boolean type. Make it!
  • define boolean_t int
  • define TRUE 1
  • define FALSE 0
  • Example
  • boolean_t xIsFive, zAsBig, result
  • xIsFive (x 5)
  • zAsBig (z gt x)
  • if (xIsFive zAsBig)
  • result TRUE

35
Naming your own type
  • Syntax
  • typedef existing-type new-type
  • Comments
  • typedef does not create a new type
  • only creates a new label for an existing type
  • makes your code easier to read

36
typedef in action
  • Example
  • typedef char string_t
  • typedef int boolean_t
  • string_t msg "No more room"
  • boolean_t full_class
  • if (num_students gt MAX_SIZE)
  • full_class TRUE

37
Pointers
  • C relies heavily on pointers
  • int i
  • int pi
  • pi i
  • pi 3

i pi
3
pi i
38
Pointers and Arrays
  • An array name by itself is a pointer to the first
    element
  • int a100
  • a 5 / same as a0 5 /
  • (a 3) 10 / same as a3 10 /
  • / Note a 3 means something else /
  • Arrays are passed by reference
  • void array_incr(int a10)
  • int i
  • for (i0 ilt10 i)
  • ai
  • array_incr(my_array)

39
Call by reference
  • / increment i by 1 /
  • void incr (int pi)
  • pi pi 1
  • main()
  • int j
  • j 4
  • incr (j)
  • printf ("j d\n", j)
  • j and i are pointers to the same integer incr
    can change the integer (side effect), but not the
    pointer

4
j
i
40
Dynamic Memory Allocation
  • Pointer errors can be nasty
  • void main ()
  • int p
  • p 5
  • Reserve space for the "pointed to" object
  • include ltstdlib.hgt
  • void main ()
  • int p
  • p (int )malloc(sizeof (int))
  • p 5
  • printf ("value at p d\n", p)
  • free (p) / must do this yourself! /

41
Structures
  • Use struct to create or define a new type
  • struct str_data
  • char string
  • int length
  • struct str_data s1, s2
  • Syntax
  • struct structure_name
  • type1 member1
  • type2 member2
  • A member of a structure is referred to by
  • structure_name.member

42
Structures, cont.
  • Example
  • struct str_data
  • char string
  • int length
  • struct str_data s1, s2
  • s1.string (char )malloc(80sizeof(char))
  • strcpy (s1.string, "How now brown cow.")
  • s1.length strlen(s1.string)
  • s2 s1 / can copy structures, pass to fcns /
  • free(s1.string)

43
Arrays of Structures
  • Example
  • define MAX_STUDENT 100
  • typedef struct / define a new type /
  • char name80
  • int name_len
  • int student_number
  • student_t
  • / create list of elements of type student_t /
  • student_t classMAX_STUDENT
  • for (i 0 i lt MAX_STUDENT i)
  • gets(classi.name)
  • classi.name_len strlen(classi.name)

44
Pointers to Structures
  • These are all equivalent
  • struct str_data list
  • ...
  • list0.length ...
  • (list).length ...
  • list-gtlength ...
  • Rules
  • p-gty is shorthand for (p).y
  • means "follow the pointer p into structure member
    y
  • more efficient to pass pointers to structs rather
    than the structs themselves

45
Self-Referential Structures
  • Example Linked List
  • This does not work
  • typedef struct
  • int data
  • node_t next
  • node_t
  • Rules
  • a structure cannot refer to its own name before
    it is defined
  • but it can contain a pointer to itself
  • how?

46
Naming your structure
  • Give the structure a name
  • typedef struct element
  • int data
  • struct element next
  • node_t
  • Rules
  • next is a pointer to a structure of type node_t
  • we can use this to create a pointer to the head
    of the list
  • node_t head (node_t ) malloc (sizeof
    (node_t))
  • How do we define the end of the list?

47
Traversing a Linked List
  • node_t p
  • p head
  • while (p ! NULL)
  • printf ("data d\n", p-gtdata)
  • p p-gtnext

data
data
head
next
next
p
p-gtnext
48
Naming Conventions
  • Consistency is bliss. Suggested format
  • Constants use all upper case
  • define TRUE 1
  • define MAX_ELEMENTS 50
  • Variables use all lower case
  • char name int num_students
  • Functions upper case for first letter of each
    world
  • float GetCompressedValue() char GetNextWord()
  • Types all lower case with a "_t" suffix (for
    type)
  • typedef struct node_t ...

49
Programming Errors I
  • include ltstdio.hgt
  • void main ()
  • int i
  • scanf ("d", i)
  • if (i 0)
  • printf ("false")
  • else
  • printf ("true")
  • Whats wrong?

50
Programming Errors I
  • include ltstdio.hgt
  • void main ()
  • int i
  • scanf ("d", i)
  • if (i 0)
  • puts ("false")
  • else
  • puts ("true")
  • The assignment, i 0, will return a value of 0,
    so the program will always output "true"
  • Use if(0 i) to be safe

51
Programming Errors II
  • include ltstdio.hgt
  • void main ()
  • int i
  • / echo one number /
  • scanf ("d", i)
  • printf ("input d\n", i)
  • Whats wrong?
  • Hint Segmentation fault / Bus error

52
Programming Errors II
  • include ltstdio.hgt
  • void main ()
  • int i
  • / echo one number /
  • scanf ("d", i)
  • printf ("input d\n", i)
  • Must provide the address of an integer if the
    function is going to assign a value to it.

53
Programming Errors III
  • include ltstdio.hgt
  • void main ()
  • int pc
  • scanf ("d", pc)
  • printf ("d\n", pc)
  • Whats wrong?

54
Programming Errors III
  • include ltstdio.hgt
  • void main ()
  • int pc
  • scanf ("d", pc)
  • printf ("d\n", pc)
  • pc is an uninitialized pointer so results are
    unpredictable --gt use malloc

55
Programming Errors IV
  • include ltstdlib.hgt
  • void main ()
  • double p
  • p malloc (sizeof (double ))
  • Whats wrong?

56
Programming Errors IV
  • include ltstdlib.hgt
  • void main ()
  • double p
  • p malloc (sizeof (double ))
  • Insufficient memory allocated for a double
    (typically, 8 bytes)
  • Use malloc (sizeof (double))

57
Programming Errors V
  • include ltstdio.hgt
  • void main ()
  • char s "hi"
  • if (s "hi")
  • printf ("Strings are equal")
  • else
  • printf ("Strings are not equal")
  • What happens?

58
Programming Errors V
  • include ltstdio.hgt
  • main ()
  • char s "hi"
  • if (s "hi")
  • puts ("Strings are equal")
  • else
  • puts ("Strings are not equal")
  • Use strcmp() to compare strings, otherwise you
    are comparing addresses.

59
Finding Bugs
  • Insert "print" statements
  • printf ("At point A, s d\n", "x", x)
  • Use a debugger to help you catch bugs in the act
  • run step-by-step
  • insert breakpoints
  • display variables

60
The GNU Debugger GDB
  • Allows you to
  • Make your program stop on specified conditions
  • Step through your programs execution line by
    line
  • Examine what has happened when your program has
    stopped or crashed.

61
Using GDB
  • Compile your program with the -g option
  • gcc -g -o prog prog.c
  • To run your program in GDB
  • gdb prog
  • (gdb) run
  • To examine your program after a crash (core
    dump)
  • prog
  • Segmentation fault (core dumped)
  • gdb prog core
  • Core was generated by prog'.
  • Program terminated with signal 11, Segmentation
    fault.
  • (gdb) ...

62
Some GDB Commands
  • Set a breakpoint
  • (gdb) break filefunction
  • Run your program
  • (gdb) run arglist
  • List 10 lines of code
  • (gdb) list
  • Display the value of an expression
  • (gdb) print expr
  • Display a value after each stoppage
  • (gdb) display expr

63
More GDB Commands
  • Execute next line (skipping function calls)
  • (gdb) next
  • Execute next line stepping into fcn calls
  • (gdb) step
  • Continue after a break
  • (gdb) cont
  • Getting help
  • (gdb) help name
  • Exiting
  • (gdb) quit

64
Debugging A Program I
  • Example (searching a linked list)
  • / search for data, return pointer to the node /
  • node_t Search(node_t head, int data)
  • node_t p
  • p head
  • do
  • if (p-gtdata data)
  • return (p)
  • else
  • p p-gtnext
  • while (p ! NULL)
  • return (NULL)

65
Debugging A Program II
  • There is a bug
  • Input
  • 1 2 3 4 -1 (values for linked list)
  • 17 (value to search for)
  • Output
  • 17 is found (! but it's not in the list)
  • 17 3 2 1 (! 4 is missing)
  • Steps to find the bug
  • start up GDB
  • gdb linklist

66
Debugging A Program III
  • set a breakpoint at the Search function
  • (gdb) break Search
  • Breakpoint 1 at 0x10ab0 file linklist.c, line
    13.
  • (gdb)
  • run the program and provide some input
  • (gdb) run
  • Starting program linklist
  • 1 2 3 4 -1 17
  • Breakpoint 1, Search (head0x21b50, data17)
  • 13 p head
  • (gdb)
  • display some variables
  • (gdb) display p
  • 1 p (node_t ) 0x20d58
  • (gdb) display p
  • 2 p data 4, next 0x20d48
  • (gdb)

67
Debugging A Program IV
  • step through the code and watch the variables
    change
  • (gdb) step
  • 15 if (p-gtdata data)
  • (gdb) display p
  • 1 p (node_t ) 0x21b50
  • (gdb) display p
  • 2 p data 4, next 0x21b40
  • (gdb) step
  • 16 return (p)
  • 2 p data 17, next 0x21b40
  • 1 p (node_t ) 0x21b50
  • We found the bug

68
Debugging A Program V
  • But there is another bug
  • Input
  • -1 (empty list)
  • 17 (value to search for)
  • Output
  • Segmentation fault (core dumped)
  • See if you can find the bug.

69
References
  • Prof. Jeremy Cooperstocks Crash Course in C,
    http//www.cim.mcgill.ca/jer/courses/C/
  • Kernighan Ritchie "The C programming
    language", 2nd edition. Prentice-Hall, 1988.
Write a Comment
User Comments (0)
About PowerShow.com