You are on page 1of 57

C Survival Guide

Lawrence Angrave

Copyright ©: Nahrstedt, Angrave, Abdelzaher 1


Copyright ©: Angrave, Abdelzaher,Nahrstedt

C in 3 slides: Pointers
 & 'address-of' (reference operator)
 * 'contents-of' (dereference operator)
 Automatic variables are temporary and stored
in the stack
 char* p; p is a pointer to a character.
*p =0; contents-of p set to 0. (Kaboom!)
 After declaring a pointer, initialize it to
something before using it. (Doh!)

2
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Instant C #2: Strings


 C strings are terminated with a null byte
 strcpy( "hello", "world" ) will crash
 strcmp(s1,s2) returns 0 if same
 argv[0] is the program name
 argv[argc] is a null pointer

3
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Instant C #3: Heap Allocation


 malloc(bytes) to reserve heap memory
 later… free(ptr)

 static char* ptr;


static variables are not stored in stack

4
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Common Causes of 'Death'*


 Uninitialized pointers
strcpy(dest,"hello");
 C Strings need null byte at the end
 Buffer overflow
 Un-initialized memory
 Too confident: not checking return
values
 Miss-use of static vs. stack variables.

*Talk like a Professional : "Segfault" / "Signal 11"


5
Review
Fix the following code if necessary
1. int p1;
What does &p1 mean? 1. if(strcmp("a","a"))
printf("same!");
2. char**argv;
What type is argv? 2. int i =4;
What type is *argv?
What type is **argv?
int *iptr;
iptr = &i;
3. main(int argc,char**argv) {
*iptr = 5;//now i=5
what is *argv ?
what is argv[argc ] ?
3. char *p;
4. What are the differences between x
p=(char*)malloc(99);
and y? strcpy("Hello",p);
char* f() { printf("%s World",p);
char *x; free(p);
static char*y;
return y;
} 4. char msg[5];
strcpy (msg,"Hello");
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Good news: You've used C++ in CS225 so…

Writing C code is easy!


 void* myfunction() {
char *p;
*p = 0;
return (void*) &p;

7
Copyright ©: Angrave, Abdelzaher,Nahrstedt

that crashes / is unpredictable


Writing C code  is easy !
 void* myfunction() {
char *p;
*p = 0;
return (void*) &p;

8
Copyright ©: Angrave, Abdelzaher,Nahrstedt

How do I write good C


programs?
 Fluency in C syntax
 Stack vs. Heap
 Key skill: read code for bugs
 (compiler warnings,if any, and testing are
insufficient)

9
Copyright ©: Angrave, Abdelzaher,Nahrstedt

100 minute challenge


 Pointers
 C character arrays & string functions
 Stack & heap allocation
 Tools:make, gcc, (gdb)

Exchange rate: 10 minutes learning = 100 minutes of debugging an MP


10
Copyright ©: Angrave, Abdelzaher,Nahrstedt

C is powerful - it's the System


Programmer's choice language

 Sun Operating System


 Linux Operating System
 BSD & Apple OS X
 Ruby, Python, JVM, gcc
 bash shell, dir
 Apache web server
http://svn.apache.org/repos/asf/httpd/httpd/trunk/server/util.c
http://www.google.com/codesearch?q=lang:c 11
Copyright ©: Angrave, Abdelzaher,Nahrstedt

The C Language Spirit


 Made by professional programmers for professional
programmers
 Very flexible, very efficient and portable
 Does not protect the programmers from themselves.
Rationale: programmers know what they are doing.
 UNIX and most “serious” system software (servers,
compilers, etc) are written in C.
 Can do everything Java and C++ can. It’ll just look
uglier in C
12
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Compiler
 gcc
 Preprocessor
 Compiler
 Linker
 See manual “man” for options: man gcc
 "Ansi-C" standards C89 versus C99
 C99: Mix variable declarations and code (for int i=…)
 C++ inline comments //a comment
 make – a compilation utility
 Google 'makefile'

13
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Programming in C

C = Variables + Instructions

14
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Programming in C

C = Variables + Instructions
char
int
float
pointer
array
… string 15
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Programming in C

C = Variables + Instructions
char assignment
int printf/scanf
float if
pointer for
array while
… string … switch 16
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Variables
Name

10,000
x Value1
10,002
y
Value2
Memory
Address Value
10,008
z Value3
10,010
p Value4
10,012
d Value5

17
Copyright ©: Angrave, Abdelzaher,Nahrstedt

The “&” Operator:


Reads “Address of”
Name

10,000
&y x Value1
10,002
y
Value2
Value
10,008
z Value3
10,010
p Value4
10,012
d Value5

18
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Pointers
Name
A pointer is a variable
10,000 whose value is the
x Value1
address of another
10,002
y
Value2
Value
10,008
z Value3
10,010
p 10,002
10,012
d Value5

19
Copyright ©: Angrave, Abdelzaher,Nahrstedt

The “*” Operator


Reads “Variable pointed to by”
Name
A pointer is a variable
10,000 whose value is the
x Value1
address of another
10,002
y
*P
Value2
Value
10,008
z Value3
10,010
p 10,002
10,012
d Value5

20
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x;
x=10;
p=&x;
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
21
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x; p #@*%!
x=10; q #@%$!

p=&x; x @*%^
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
22
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x; p #@*%!
x=10; q #@%$!

p=&x; x 10
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
23
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x; p
x=10; q #@%$!

p=&x; x 10
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
24
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x; p
x=10; q #@%$!

p=&x; x 11
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
25
Copyright ©: Angrave, Abdelzaher,Nahrstedt

What is the Output?


main() {
int *p, q, x; p
x=10; q 11
p=&x; x 11
*p=x+1;
q=x;
printf (“Q = %d\n“, q);
}
26
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Cardinal Rule: Must Initialize


Pointers before Using them
int *p; BAD
*p = 10;

27
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Cardinal Rule: Must Initialize


Pointers before Using them
int *p;
*p = 10;

p #@*%!
??
Pointing somewhere
random

28
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Cardinal Rule: Must Initialize


Pointers before Using them
int *p;
*p = 10;

p #@*%!
10
#@*%!

29
Copyright ©: Angrave, Abdelzaher,Nahrstedt

How to Initialize Pointers

30
Copyright ©: Angrave, Abdelzaher,Nahrstedt

How to Initialize Pointers


 Set pointer equal to location of known
variable

int *p;
int x;

p=&x;
31
Copyright ©: Angrave, Abdelzaher,Nahrstedt

How to Initialize Pointers


 Use malloc()

int *p;

p=(int*) malloc (sizeof (int));

32
Copyright ©: Angrave, Abdelzaher,Nahrstedt

How to Initialize Pointers


 Create an Array

int p[10];

Same as:
int *p;
p=(int*) malloc (10*sizeof (int));
33
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Arrays
int p[5];
p
p[0]
p[1]
Name of array (is a pointer)
p[2]
p[3]
p[4]
Shorthand:
*(p+1) is called p[1]
*(p+2) is called p[2]
etc..
34
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Example
int y[4];
y[1]=6; y

y[2]=2; y[0]
y[1] 6
y[2] 2
y[3]

35
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Array Name as Pointer


 What’s the difference between the examples below:

Example 1:
int z[8];
int *q;
q=z;

Example 2:
int z[8];
int *q;
q=&z[0];
36
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Array Name as Pointer


 What’s the difference between the examples below:

Example 1:
int z[8];
int *q; NOTHING!!
q=z;
x (the array name) is a pointer
Example 2:
to the beginning of the array,
int z[8];
int *q; which is &x[0]
q=&z[0];
37
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Example:
How much is y at the end:
int y, x, *p;

x = 20;
*p = 10;
y = x + *p;

38
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Example:
How much is y at the end:
int y, x, *p;

BAD!!
x = 20; Dereferencing an unitialized pointer
*p = 10; will likely segfault or overwrite
something!
y = x + *p;
Segfault = unauthorized memory
access
39
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Question:
 What’s the difference between
int* q;
int q[5];

 What’s wrong with:


int ptr[2];
ptr[1] = 1;
ptr[2] = 2;
40
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Question:
 What is the value of b[2] at the end?

int b[3];
int* q;

b[0]=48; b[1]=113; b[2]=1;


q=b;
*(q+1)=2;
b[2]=*b
b[2]=b[2]+b[1];

41
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Strings
(Null-terminated Arrays of Char)
 Example
char s[5];
 Strings are arrays that contain the string

characters followed by a “Null” character to


indicate end of string.
 Do not forget to leave room for the null character
s
s[0]
s[1]
s[2]
s[3]
s[4]
42
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Conventions
Strings
 “string”

 “c”

Character
 ‘c’

43
Copyright ©: Angrave, Abdelzaher,Nahrstedt

String Operations
 strcpy
 strlen
 strcat
 strcmp

44
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strcpy, strlen
Syntax:
strcpy(ptr1, ptr2);
    where ptr1 and ptr2 are pointers to char
value = strlen(ptr);
    where value is an integer and
    ptr is a pointer to char

Example:
int len;
char str[15];
strcpy (str, "Hello, world!");
len = strlen(str); 45
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strcpy, strlen
What’s wrong with

char str[5];
strcpy (str, "Hello");

46
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strncpy
Syntax:
strncpy(ptr1, ptr2, num);
    where ptr1 and ptr2 are pointers to char
num is the number of characters to be copied

Example:
int len;
char str1[15], str2[15];
strcpy (str1, "Hello, world!");
strncpy (str2, str1, 5); 47
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strncpy
Syntax:
strncpy(ptr1, ptr2, num);
    where ptr1 and ptr2 are pointers to char
num is the number of characters to be copied
Caution: strncpy blindly copies the
Example: characters. It does not voluntarily append
int len; the string-terminating null character.
char str1[15], str2[15];
strcpy (str1, "Hello, world!");
strncpy (str2, str1, 5); 48
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strcat
 Syntax: strcat(ptr1, ptr2);
    where ptr1 and ptr2 are pointers to char

Concatenates the two null terminates strings


yielding one string (pointed to by ptr1).

char S[25] = "world!";


char D[25] = "Hello, ";
strcat(D, S);
49
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strcat
Example

 What’s wrong with:

char S[25] = "world!";


strcat(“Hello, ”, S);

50
Copyright ©: Angrave, Abdelzaher,Nahrstedt

strcmp
 Syntax: diff = strcmp(ptr1, ptr2);
    where diff is an integer and
    ptr1 and ptr2 are pointers to char
 Returns zero if strings are identical

int diff;
char s1[25] = "pat";
char s2[25] = "pet";
diff = strcmp(s1, s2);
51
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Math: Increment and


Decrement Operators
Example 1:
int x, y, z, w;
y=10; w=2;
x=++y;
z=--w;

Example 2:
int x, y;
y=10; w=2;
x=y++;
z=w--; 52
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Math: Increment and


Decrement Operators
Example 1:
int x, y, z, w;
y=10; w=2; First increment/decrement then assign result
x=++y; x is11, z is 1

z=--w;

Example 2:
int x, y;
First assign then increment/decrement
y=10; w=2; x is 10, z is 2
x=y++;
z=w--; 53
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Math: Increment and Decrement


Operators on Pointers
Example 1:
int a[2];
int number1, number2, *p;
a[0]=1; a[1]=10; a[2]=100;
p=a;
number1 = *p++;
number2 = *p;

What will number1 and number2 be at the end?

54
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Math: Increment and Decrement


Operators on Pointers
Example 1:
int a[2];
int number1, number2, *p;
a[0]=1; a[1]=10; a[2]=100;
Hint: ++ increments pointer p not variable *p
p=a;
number1 = *p++;
number2 = *p;

What will number1 and number2 be at the end?

55
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Logic: Relational (Condition)


Operators
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

56
Copyright ©: Angrave, Abdelzaher,Nahrstedt

Logic Example
if (a == b) printf (“Equal.”);
else printf (“Not Equal.”);

 Question: what will happen if I replaced the above


with:
if (a = b) printf (“Equal.”);
else printf (“Not Equal.”);
57

You might also like