Systems Programming 1. Basic C Programming Guillaume Pierre Fall - - PDF document

systems programming
SMART_READER_LITE
LIVE PREVIEW

Systems Programming 1. Basic C Programming Guillaume Pierre Fall - - PDF document

0 Systems Programming 1. Basic C Programming Guillaume Pierre Fall 2007 http://www.cs.vu.nl/ gpierre/courses/sysprog/ 1 Table of contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . 2 2. Data types . . . .


slide-1
SLIDE 1

Systems Programming

  • 1. Basic C Programming

Guillaume Pierre Fall 2007 http://www.cs.vu.nl/∼gpierre/courses/sysprog/

1

Table of contents

  • 1.

Introduction . . . . . . . . . . . . . . . . . . . . . . . 2

  • 2.

Data types . . . . . . . . . . . . . . . . . . . . . . . . 14

  • 3.

Control Structures . . . . . . . . . . . . . . . . . . . . 25

  • 4.

Variables . . . . . . . . . . . . . . . . . . . . . . . . . 29

  • 5.

Functions . . . . . . . . . . . . . . . . . . . . . . . . . 36

  • 6.

The C Preprocessor . . . . . . . . . . . . . . . . . . . 43

slide-2
SLIDE 2
  • 1. Introduction

2

1. Introduction

  • 1. Introduction

3

Literature

◮ Reader (C for Java programmers)

⊲ Available on the Web site

◮ Books

⊲ The C Programming Language (Kernighan, Ritchie) ⊲ The Complete Reference (Schildt) ⊲ The C Puzzle Book (Feuer) ⊲ Many others available....

◮ Check on Amazon.com or Google

slide-3
SLIDE 3
  • 1. Introduction

4

Overview

◮ Very short history of C ◮ Overview of the differences between C and Java ◮ The C language (keywords, types, functies, etc.) ◮ Preprocessor ◮ Next lecture: pointers ◮ Then: memory management, files

  • 1. Introduction

5

History of C

◮ Created in the mid-70’s as a follow up to the ’B’ and ’BCPL’ languages ◮ Standardized between 1983 and 1988 (ANSI C) ◮ Syntax is the basis for other languages like C++, Objective-C, Java and C#

slide-4
SLIDE 4
  • 1. Introduction

6

History of C

◮ Development of C is related to development of Unix ◮ Unix initially programmed using assembly language

⊲ Assembly instructions are very low-level ⊲ Assembly instructions are machine specific

◮ To make Unix more portable a high-level and portable language was needed ◮ The result was C

  • 1. Introduction

7

C vs. Assembler

◮ Compared to Assembler, C is:

⊲ High level (C has functions, while and for loops, etc.) ⊲ Portable (only the C compiler must be ported for each platform, all applications stay the same)

slide-5
SLIDE 5
  • 1. Introduction

8

C vs. Java [1/2]

◮ C is procedural, not object oriented

⊲ C has no objects, interfaces or packages ⊲ A program only consists of functions and data

◮ C is compiled, not interpreted

⊲ Translated directly to assembly language ⊲ Faster, less portable and very hard to debug.

◮ C has no array bounds, null pointer or cast checks

⊲ You have to detect and handle all problems yourself

◮ C has no garbage collector

⊲ You have to do all of the memory management yourself

  • 1. Introduction

9

C vs. Java [2/2]

◮ C has pointers

⊲ Similar to Java references but. . . ⊲ . . . they can be used in calculations (pointer arithmetic) ⊲ Allows you to use the location of data in computations (not just the value) ⊲ Useful, powerful and a debugging nightmare!

◮ Compared to Java, C is a low-level language

⊲ You can and must do everything yourself ⊲ Suitable for low-level software like device-drivers, communication libraries, operating systems, etc.

slide-6
SLIDE 6
  • 1. Introduction

10

C can be quite complex. . .

This program computes and prints the first 800 decimals of π:

long a=10000,b,c=2800,d,e,f[2801],g; int main(){ for(;b-c;)f[++b]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a) for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b); }

◮ Fortunately, you will never have to write such unreadable code ;-)

  • 1. Introduction

11

Program Structure (1)

A Java program consists of:

  • Several classes,
  • ne class per file.
  • A main method in one of

these classes.

  • External class libraries (jar

files). A C program consists of:

  • Several functions in

any number of files.

  • A main function in one of

these files.

  • Possibly some header files.
  • External libraries and their

header files.

slide-7
SLIDE 7
  • 1. Introduction

12

Example program

/* This is a comment */ #include <stdio.h> /* stdio.h is a standard header file */ int main() { /* this function is always called first */ printf("Hello, world!\n"); /* \n is the ’new line’ character */ return 0; /* main() should return 0 when it is finished */ }

  • 1. Introduction

13

Compile and execute your program

◮ Compile your program like this:

gcc -Wall hello.c

⊲ This creates an executable file called a.out ⊲ ’-Wall’ means ’please output warnings about my program’

☞ It is better to always use this option. . . ☞ . . . and read the warnings! (even though they are sometimes hard to understand)

◮ Execute your program:

$ a.out Hello, world! $

◮ If you want to call your program with a different name:

gcc -Wall -o my_program_name hello.c

slide-8
SLIDE 8
  • 2. Data types

14

2. Data types

  • 2. Data types

15

Basic data types

◮ C knows the following data types:

⊲ char is a single character

char x=’a’, y=’\n’, z=’\0’;

  • Characters are defined between simple quotes (’a’)
  • Double quotes (”a”) mean something different

⊲ short, int and long are short, normal and long integers

int a=3, b=-2; long c=1234567890;

⊲ unsigned short, unsigned int and unsigned long are unsigned versions of short, int and long. ⊲ float and double are normal and double floating-point numbers:

float d=3.14159, e=-3.01; f=6.022e23;

◮ Did you notice? There is no ’string’ data type here. . .

slide-9
SLIDE 9
  • 2. Data types

16

Arrays

◮ Defining an array is easy:

int a[3]; /* a is an array of 3 integers */

◮ Array indexes go from 0 to n-1:

a[0] = 2; a[1] = 4; a[2] = a[0] + a[1]; int x = a[a[0]]; /* what is the value of x? */

⊲ Beware: in this example a[3] does not exist, but your compiler will not complain if you use it!

  • But your program may have a very strange behavior. . .

◮ You can create multidimensional arrays:

int matrix[3][2]; matrix[0][1] = 42;

  • 2. Data types

17

Strings

◮ A string is an array of characters:

char hello[15]="Hello, world!\n";

◮ Unlike in Java, you must decide in advance how many characters can be stored in a string.

⊲ You cannot change the size of the array afterwards

◮ Beware: strings are always terminated by a NULL character: ’\0’

⊲ For example, "Hello" is string of 6 characters: H e l l

  • \0
slide-10
SLIDE 10
  • 2. Data types

18

Manipulating arrays

◮ You cannot copy an array into another directly

⊲ You must copy each element one at a time

int a[3] = {12,24,36}; int b[3]; b = a; /* This will NOT work! */ b[0]=a[0]; b[1]=a[1]; b[2]=a[2]; /* This will work */

  • 2. Data types

19

Manipulating strings [1/2]

◮ There are standard function to manipulate strings:

⊲ strcpy(destination, source) will copy string source into string destination:

char a[15] = "Hello, world!\n"; char b[15]; strcpy(b,a);

☞ Attention: strcpy does not check that destination is large enough to accomodate source.

char c[10]; strcpy(c,a); /* This will get you in BIG trouble */

slide-11
SLIDE 11
  • 2. Data types

20

Manipulating strings [2/2]

◮ Instead of strcpy it is always better to use strncpy:

⊲ strncpy takes one more parameter to indicate the maximum number of characters to copy:

char a[15] = "Hello, world!\n"; char c[10]; strncpy(c,a,9); /* Why 9 instead of 10? */

  • 2. Data types

21

Structures

◮ You can build higher-level data types by creating structures:

struct Complex { float real; float imag; }; struct Complex number; number.real = 3.2; number.imag = -2; struct Parameter { struct Complex number; char description[32]; }; struct Parameter p; p.number.real = 42; p.number.imag = 12.3; strncpy(p.description, "My nice number", 31);

slide-12
SLIDE 12
  • 2. Data types

22

Enumerations

◮ enum is used to create a number of related constants

enum workdays {monday, tuesday, wednesday, thursday, friday }; enum workdays today; today = tuesday; today = friday; enum weekend {saturday = 10, sunday = 20};

  • 2. Data types

23

Data type sizes

◮ When doing systems programming it is often important to know how much memory is used for a variable.

⊲ Unfortunately, the size of data types depends on the machine you are working on: char short int long float double pointer Intel x86 1 2 4 4 4 8 4 AMD64 1 2 4 8 4 8 8 Sparc 1 2 4 4 4 8 4

◮ To get the actual size of a type or a variable, use sizeof:

char a[32]; int s1 = sizeof(char); int s2 = sizeof(s1); int s3 = sizeof(a); /* the size of a is 32 bytes */ int s4 = sizeof(Complex);

slide-13
SLIDE 13
  • 2. Data types

24

Using the right-sized integer

◮ Sometimes you really want to decide whether wou want an 8-bit, 16-bit or 32-bit integer

⊲ For example, when you need to process audio files. . .

◮ In this case (and this case only), use the following types:

#include <sys/types.h> int8_t a; int16_t b; int32_t c;

  • 3. Control Structures

25

3. Control Structures

slide-14
SLIDE 14
  • 3. Control Structures

26

Comparison operators

◮ The following operators are defined for basic data types:

if (a == b) { ... } if (a != b) { ... } if (a < b) { ... } if (a <= b) { ... } if (a > b) { ... } if (a >= b) { ... } if ((a==b) && (c>d)) {...} /* logical AND */ if ((a==b) || (c>d)) {...} /* logical OR */

◮ There is no boolean type in C. We use integers instead:

⊲ 0 means FALSE ⊲ Any other value means TRUE

int x; if (x) {...} /* Equivalent to: if (x!=0) {...} */ if (!x) {...} /* Equivalent to: if (x==0) {...} */

  • 3. Control Structures

27

Classical bugs

✿✿✿

Do

✿✿✿✿✿

not ✿✿✿✿✿✿✿✿✿ confuse ✿✿✿✿ ’=’ ✿✿✿✿✿ and ✿✿✿✿✿✿✿ ’==’!

if (x=y) { ... } /* This is correct C but it means something different */ if (x=3) { /* always executed */ } if (x=0) { /* never executed */ }

✿✿✿

Do

✿✿✿✿✿

not ✿✿✿✿✿✿✿✿✿ confuse ✿✿✿✿ ’&’ ✿✿✿✿✿ and ✿✿✿✿✿✿✿ ’&&’!

if (x&y) { ... } /* This is correct C but it means something different */ if (x|y) { ... }

slide-15
SLIDE 15
  • 3. Control Structures

28

Control structures

if (x>0) { ... } while (x>0) { ... } do { ... } while (x>0); for (x=0;x<3;x++) { ... }

  • 4. Variables

29

4. Variables

slide-16
SLIDE 16
  • 4. Variables

30

Variables

◮ C has two kinds of variables:

⊲ Local (declared inside of a function) ⊲ Global (declared outside of a function)

int global; void function() { int local; }

  • 4. Variables

31

Local Variables [1/2]

◮ Can only be used inside a function (like in Java) ◮ Declaration must be done in beginning of function

/* ok */ void func1() { int a, b; a = 0; b = 1; } /* ok */ void func2() { int a = 0; int b = 1; } /* wrong */ void func3() { int a = 0; a++; int b = 1; }

slide-17
SLIDE 17
  • 4. Variables

32

Local Variables [2/2]

◮ Also in for loops !

/* ok */ void function1(void) { int a, b; a = 10; for (b=0;b<a;b++) { } } /* wrong */ void function2(void) { int a; a = 10; for (int b=0;b<a;b++) { } }

  • 4. Variables

33

Static local variables

◮ Declaring a static variable means it will persist across multiple calls to the function

void foo() { static int i=0; i++; printf("i=%d\n",i); /* This prints the value of i on the screen */ } int main() { int i; for (i=0;i<3;i++) foo(); }

This program will output this:

i=1 i=2 i=3

slide-18
SLIDE 18
  • 4. Variables

34

Global Variables

◮ Global variables have file scope

⊲ They can be used by all functions in the file ⊲ They must be declared before they can be used

int i = 7; /* i is a global variable */ void foo() { printf("i=%d\n", i); } int main() { printf("i=%d\n", i); foo(); }

  • 4. Variables

35

Classical mistake

◮ When you declare a variable, its value is not initialized

⊲ The variable may have any value (depending what was previously stored in this piece of memory) ⊲ Always think of initializing variables before you use them!

int y; if (y) { /* who knows what will happen??? */ } while (y--) { /* same here */ }

slide-19
SLIDE 19
  • 5. Functions

36

5. Functions

  • 5. Functions

37

Functions

◮ In C, functions can be defined in two ways:

int foo() { /* function foo returns an int */ ... return 123; } void bar(int p1, double p2) { /* function bar returns nothing */ ... }

◮ Calling a function is easy:

int i = foo(); /* call function foo() */ bar(2, -4.321); /* call function bar() */

slide-20
SLIDE 20
  • 5. Functions

38

Standard C library

◮ The C language always comes with the standard C library

⊲ A collection of functions to help you write programs ⊲ About memory, input/output, strings, time, etc.

◮ I will describe only a few important functions here

⊲ For more information, read “man pages”:

  • You want information about function strncpy()? (cf. slide 20)

☞ Type the command: “man strncpy” and see what happens (type ’space’ to read on, ’b’ to move up or ’q’ to exit)

  • Type: “man man” for information about this weird “man” command
  • There are “man pages” for (almost) all programs and functions

⊲ A full reference can be found (for example) in http://www.gnu.org/software/libc/manual/

  • 5. Functions

39

’man strncpy’ example

$ man strncpy NAME strcpy, strncpy - copy a string SYNOPSIS #include <string.h> char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); DESCRIPTION The strcpy() function copies the string pointed to by src (including the terminating ~\0~ character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. The strncpy() function is similar, except that not more than n bytes of :

slide-21
SLIDE 21
  • 5. Functions

40

printf()

◮ printf is the standard print function in C

⊲ There are many variants of it (fprintf, sprintf, etc.)

◮ printf() is declared in the standard header file stdio.h

☞ You must add “#include <stdio.h>” before using printf()

◮ printf() takes the following arguments:

⊲ One “format string” ⊲ Any number of variables

◮ Example:

printf("This is an int: %d\n and this is a string: %s\n", 12, "mystring");

◮ printf() will format the string:

⊲ Replace ’%d’ with the first variable: ’12’ ⊲ Replace ’%s’ with the second variable: ”mystring”

  • 5. Functions

41

printf() examples

#include <stdio.h> | | int main(void) { | int val = 5; | char c = ’a’; | char str[] = "world"; | | printf("Hello world\n"); | Hello world printf("Hello %d World\n", val); | Hello 5 World printf("%d %c World\n", val, c); | 5 a World printf("Hello %s\n", str); | Hello world printf("Hello %d\n", str); | ** wrong! ** return 0; | } |

slide-22
SLIDE 22
  • 5. Functions

42

printf format strings

%d signed int %u unsigned int %x hexadecimal unsigned int %c character %f double and float %s string %% to print a %

  • 6. The C Preprocessor

43

6. The C Preprocessor

slide-23
SLIDE 23
  • 6. The C Preprocessor

44

What are all these #include things by the way?

◮ The C compiler works in 3 phases:

  • 1. Pre-process source files
  • 2. Compile source files into object files
  • 3. Link object files into an executable

◮ #include <stdio.h> means “include the contents of standard file stdio.h here”

  • 1. Standard files are usually located in directory /usr/include
  • 2. /usr/include/stdio.h may contain #include statements itself...

◮ You can use #include to include your own files into each

  • ther:

⊲ #include "myfile.h" means: “include file myfile.h (from the current directory) here” ⊲ Included files usually have extension “.h” (header)

  • 6. The C Preprocessor

45

Other preprocessor directives

◮ The preprocessor removes all comments (/* ... */ ) ◮ #define FOO 3

⊲ The preprocessor will replace the string “FOO” with the string “3” in the rest of the program

◮ Be careful with #include. . .

⊲ It is easy (and often wrong) to include the same file twice ⊲ You can “protect” your header files like this:

#ifndef _MY_HEADER_H_ #define _MY_HEADER_H_ ... #endif

⊲ What will happen if a file includes my header.h twice?

slide-24
SLIDE 24
  • 6. The C Preprocessor

46

Exercises [1/2]

These exercises are intended to help you practice the contents of this lecture. You do not need to send your programs to me. If you face difficulties when doing them, ask a question to the mailing-list or at the next Q&A session! Of course, feel free to invent more exercises. . .

  • 1. Write a program which defines an integer, a float, a character and a

string, then displays them on screen.

  • 2. Write a program which computes and displays fib(15):
  • fib(0) = 0, fib(1) = 1
  • If n > 1 then fib(n) = fib(n − 1) + fib(n − 2)
  • 6. The C Preprocessor

47

Exercises [2/2]

  • 3. Update your fib program to count how many times you called the

recursive function

  • Using a global variable
  • Using a static variable

Why can you display the value of the global variable but not the static variable at the end of the main() function?

  • 4. Type all programs with wrong syntaxes mentionned in these slides.

Which messages does the compiler display? If an executable program has been generated, what is its output?

Beware: sometimes wrong programs can generate correct output; it does not mean that your program is correct, it just means that you have been lucky. Most often these bugs show up when we grade those programs ;-(

  • 5. Check the man page of strncpy: what happens if the source string is

too long to be copied?