Copyright ©: University of Illinois CS 241 Staff1 C Survival Guide.

Slides:



Advertisements
Similar presentations
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Advertisements

Dynamic Memory Management
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 Memory Allocation Professor Jennifer Rexford COS 217.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Informática II Prof. Dr. Gustavo Patiño MJ
CPSC 388 – Compiler Design and Construction
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CSc 352 C : Arrays, Structs, Pointers
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
1 Dynamic Memory Management. 2 What’s worse?  50% of instructions/data are cache misses (fetched from RAM)  1% of instructions/data are page faults.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Outline Midterm results Static variables Memory model
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
1 C Basics. 2 The C Language Spirit Made by professional programmers for professional programmers Very flexible, very efficient, very liberal Does not.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Dynamic Memory Management Jennifer Rexford 1. 2 Goals of this Lecture Dynamic memory management techniques Garbage collection by the run-time system (Java)
1 C Basics. 2 The C Language Spirit Made by professional programmers for professional programmers Very flexible, very efficient, very liberal Does not.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
CSC 533: Programming Languages Spring 2016
Dynamic Storage Allocation
Computer Organization and Design Pointers, Arrays and Strings in C
CSC 533: Programming Languages Spring 2015
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Pointers and Arrays Beyond Chapter 16
Homework Continue with K&R Chapter 5 Skipping sections for now
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2019
Presentation transcript:

Copyright ©: University of Illinois CS 241 Staff1 C Survival Guide

Announcements Homework 1 posted  Due 11am, August 31  Submit via svn Piazza access code: ________ Discussion sections will be held this week Copyright ©: University of Illinois CS 241 Staff2

Good news: Writing C code is easy! void* myfunction() { char *p; *p = 0; return (void*) &p; } Copyright ©: University of Illinois CS 241 Staff3

Bad news: Writing BAD C code is easy! void* myfunction() { char *p; *p = 0; return (void*) &p; } Copyright ©: University of Illinois CS 241 Staff4 What is wrong with this code?

How do I write good C programs? Fluency in C syntax Stack (static) vs. Heap (dynamic) memory allocation Key skill: read code for bugs  Do not rely solely on compiler warnings, if any, and testing Key skill: debugging  Learn to use a debugger. Don’t only rely on printf s! Copyright ©: University of Illinois CS 241 Staff5

Why C instead of Java? C helps you learn how to write large-scale programs  C is lower-level C provides more opportunities to create abstractions  C has some flaws C’s flaws motivate discussions of software engineering principles C helps you get “under the hood”  C facilitates language levels tour C is closely related to assembly language  C facilitates services tour Many existing servers/systems written in C Copyright ©: University of Illinois CS 241 Staff6

C vs. Java: Design Goals Java design goals  Support object-oriented programming  Allow same program to run on multiple operating systems  Support using computer networks  Execute code from remote sources securely  Adopt the good parts of other languages Implications for Java  Good for application-level programming  High-level (insulates from assembly language, hardware)  Portability over efficiency  Security over efficiency Copyright ©: University of Illinois CS 241 Staff7

C vs. Java: Design Goals C design goals  Support structured programming  Support development of the Unix OS and Unix tools As Unix became popular, so did C Implications for C  Good for systems-level programming  Low-level  Efficiency over portability  Efficiency over security Anything you can do in Java you can do in C – it just might look ugly in C! Copyright ©: University of Illinois CS 241 Staff8

C vs. C++ C++ is “C with Classes”  C enhanced with objects C has some shortcomings compared to C++  C++ has objects, a bigger standard library (e.g., STL), parameterized types, etc.  C++ is a little bit more strongly typed Programming Challenge  All syntax you use in this class is valid for C++  Not all C++ syntax you’ve used, however, is valid for C 9Copyright ©: University of Illinois CS 241 Staff

A Few Differences between C and C++ Input/Output  C does not have “iostreams”  C++: cout<<"hello world“<<endl;  C: printf("hello world\n“); Heap memory allocation  C++: new/delete int *x = new int[8]; delete(x);  C: malloc()/free() int *x = malloc(8 * sizeof(int)); free(x); 10Copyright ©: University of Illinois CS 241 Staff

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 utility to build executables 11Copyright ©: University of Illinois CS 241 Staff

Programming in C C = Variables + Instructions 12Copyright ©: University of Illinois CS 241 Staff

Programming in C C = Variables + Instructions 13 int char float string … pointer array Copyright ©: University of Illinois CS 241 Staff

Programming in C C = Variables + Instructions 14 … printf/scanf assignment if switch … for while int char float string pointer array Copyright ©: University of Illinois CS 241 Staff14

What we’ll show you You already know a lot of C from C++: int my_fav_function(int x) { return x+1; } Key concepts for this lecture:  Pointers  Memory allocation  Arrays  Strings Theme: how memory really works 15Copyright ©: University of Illinois CS 241 Staff

Instant C in 3 slides: Pointers Data type that “points to” a value in memory, using its address Reference operator: &  address-of Dereference operator: *  contents-of Automatic variables  Temporary and stored in the stack Character pointers: char* p;  *p =0;  contents-of p set to 0. (Kaboom!) Initialization  Initialize a pointer to something before using it. (Doh!) 16Copyright ©: University of Illinois CS 241 Staff

Instant C in 3 slides: Pointers Data type that “points to” a value in memory, using its address Reference operator: &  address-of Dereference operator: *  contents-of Automatic variables  Temporary and stored in the stack Character pointers: char* p;  *p =0;  contents-of p set to 0. (Kaboom!) Initialization  Initialize a pointer to something before using it. (Doh!) 17Copyright ©: University of Illinois CS 241 Staff int x=4; int *y = &x; Question: What is the value of y?

Instant C in 3 slides: Pointers Data type that “points to” a value in memory, using its address Reference operator: &  address-of Dereference operator: *  contents-of Automatic variables  Temporary and stored in the stack Character pointers: char* p;  *p =0;  contents-of p set to 0. (Kaboom!) Initialization  Initialize a pointer to something before using it. (Doh!) 18Copyright ©: University of Illinois CS 241 Staff int x=4; int *y = &x; int a = *y; int b = y; Question: What are the values of a and b ?

Instant C in 3 slides: Pointers Data type that “points to” a value in memory, using its address Reference operator: &  address-of Dereference operator: *  contents-of Automatic variables  Temporary and stored in the stack Character pointers: char* p;  *p =0;  contents-of p set to 0. (Kaboom!) Initialization  Initialize a pointer to something before using it. (Doh!) 19Copyright ©: University of Illinois CS 241 Staff void main() { func(); } void* func() { int x=3; } Question: What happens to x after func() returns?

Instant C in 3 slides: Pointers Data type that “points to” a value in memory, using its address Reference operator: &  address-of Dereference operator: *  contents-of Automatic variables  Temporary and stored in the stack Character pointers: char* p;  *p =0;  contents-of p set to 0. (Kaboom!) Initialization  Initialize a pointer to something before using it. (Doh!) 20Copyright ©: University of Illinois CS 241 Staff void* func() { int* w; *w = 0 } Question: What does this code output?

Instant C #2: Strings Unlike C++ and Java, C does not have a native string type  Instead, use arrays of characters terminated with a null byte Functions  strcpy("hello", "world") will crash  strcmp(s1,s2) returns 0 if s1==s2 Arguments  argv[0] is the name of the executable  argv[argc] is a null pointer 21Copyright ©: University of Illinois CS 241 Staff

Instant C #3: Dynamic Memory Allocation Allocation  malloc(bytes) to reserve memory Clean up  free(ptr) to free up memory Dynamically allocated memory is stored on the “heap”  Static variables are stored on the “stack”  You often use static variables (pointers) to refer to and manipulate heap memory  e.g., char* c = malloc(sizeof(char)) 22Copyright ©: University of Illinois CS 241 Staff

Common Causes of 'Death' 1. Uninitialized pointers char *dest; strcpy(dest,"hello"); 2. C Strings need a null byte at the end 3. Buffer overflow 4. Un-initialized memory 5. Too confident: not checking return values 6. Misuse of static vs. stack variables. 23Copyright ©: University of Illinois CS 241 Staff

Pointers Copyright ©: University of Illinois CS 241 Staff24

Variables 10,000 10,002 10,008 10,010 10,012 … Value1 Value2 Value3 Value4 Value5 x y z p d Memory Address Name Value intx; doubley; floatz; double*p; intd; Type of each variable (also determines size) 25Copyright ©: University of Illinois CS 241 Staff

The “&” Operator: Reads “Address of” 10,000 10,002 10,008 10,010 10,012 … Value1 Value2 Value3 Value4 Value5 x y z p d Name Value &y 26Copyright ©: University of Illinois CS 241 Staff

Pointers 10,000 10,002 10,008 10,010 10,012 … Value1 Value2 Value3 10,002 Value5 x y z p d Name Value A pointer is a variable whose value is the address of another Copyright ©: University of Illinois CS 241 Staff27

The “*” Operator Reads “Variable pointed to by” 10,000 10,002 10,008 10,010 10,012 … Value1 Value2 Value3 10,002 Value5 x y z p d Name Value A pointer is a variable whose value is the address of another *p Copyright ©: University of Illinois CS 241 Staff28

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } Copyright ©: University of Illinois CS 241 Staff29

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } p q x Copyright ©: University of Illinois CS 241 Staff30

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } p q x Copyright ©: University of Illinois CS 241 Staff31

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } p q x Copyright ©: University of Illinois CS 241 Staff32

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } p q x Copyright ©: University of Illinois CS 241 Staff33

What is the Output? main() { int *p, q, x; x=10; p=&x; *p=x+1; q=x; printf (“Q = %d\n“, q); } 11 p q x Copyright ©: University of Illinois CS 241 Staff34

Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; GOOD or BAD? Copyright ©: University of Illinois CS 241 Staff35

Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; p ?? Pointing somewhere random BAD! Copyright ©: University of Illinois CS 241 Staff36

Cardinal Rule: Must Initialize Pointers before Using them int *p; *p = 10; p write to address: 10 Copyright ©: University of Illinois CS 241 Staff37

Memory allocation Copyright ©: University of Illinois CS 241 Staff38

Memory allocation Two ways to dynamically allocate memory Stack  Named variables in functions Allocated for you when you call a function Deallocated for you when function returns Heap  Memory on demand You are responsible for all allocation and deallocation Copyright ©: University of Illinois CS 241 Staff39

Allocating and deallocating heap memory Dynamically allocating memory  Programmer explicitly requests space in memory  Space is allocated dynamically on the heap  E.g., using “malloc” in C, “new” in Java Dynamically deallocating memory  Must reclaim or recycle memory that is never used again  To avoid (eventually) running out of memory “Garbage”  Allocated blocks in heap that will not be used again  Can be reclaimed for later use by the program Copyright ©: University of Illinois CS 241 Staff40

Option #1: Garbage Collection Run-time system does garbage collection (Java)  Automatically determines which objects can’t be accessed  And then reclaims the resources used by these objects Copyright ©: University of Illinois CS 241 Staff41 Object x = new Foo() ; Object y = new Bar() ; x = new Quux() ; if (x.check_something()) { x.do_something(y) ; } System.exit(0) ; Object Foo() is never used again!

Challenges of Garbage Collection Detecting the garbage is not always easy  long char z = x ;  x = new Quux();  Run-time system cannot collect all the garbage Detecting the garbage introduces overhead  Keeping track of references to object (e.g., counters)  Scanning through accessible objects to identify garbage  Sometimes walking through a large amount of memory Cleaning the garbage leads to bursty delays  E.g., periodic scans of the objects to hunt for garbage  Leads to unpredictable “freezes” of the running program  Very problematic for real-time applications … though good run-time systems avoid long freezes 42

Option #2: Manual Deallocation Programmer deallocates the memory (C and C++)  Manually determines which objects can’t be accessed  And then explicitly returns those resources to the heap  E.g., using “free” in C or “delete” in C++ Advantages  Lower overhead  No unexpected “pauses”  More efficient use of memory Disadvantages  More complex for the programmer  Subtle memory-related bugs  Can lead to security vulnerabilities in code 43

Manual deallocation can lead to bugs Dangling pointers  Programmer frees a region of memory  … but still has a pointer to it  Dereferencing pointer reads or writes nonsense values Copyright ©: University of Illinois CS 241 Staff44 int main(void) { char *p; p = malloc(10); … free(p); … printf(“%c\n”,*p); } May print nonsense character

Manual deallocation can lead to bugs Memory leak  Programmer neglects to free unused region of memory  So, the space can never be allocated again  Eventually may consume all of the available memory Copyright ©: University of Illinois CS 241 Staff45 void f(void) { char *s; s = malloc(50); } int main(void) { while (1) f(); } Eventually, malloc() returns NULL

Manual deallocation can lead to bugs Double free  Programmer mistakenly frees a region more than once  Leading to corruption of the heap data structure  … or premature destruction of a different object Copyright ©: University of Illinois CS 241 Staff46 int main(void) { char *p, *q; p = malloc(10); … free(p) q = malloc(10); free(p) } Might free space allocated by q!

Heap memory allocation C++:  new and delete allocate memory for a whole object C:  malloc and free deal with unstructured blocks of bytes void* malloc(size_t size); void free(void* ptr); 47Copyright ©: University of Illinois CS 241 Staff

Example int* p; p = (int*) malloc(sizeof(int)); *p = 5; free(p); Cast to the right type How many bytes do you want? Copyright ©: University of Illinois CS 241 Staff48

I’m hungry. More bytes plz. int* p = (int*) malloc(10 * sizeof(int)); Now I have space for 10 integers, laid out contiguously in memory. What would be a good name for that...? 49Copyright ©: University of Illinois CS 241 Staff

Arrays Contiguous block of memory  Fits one or more elements of some type Two ways to allocate  named variable int x[10];  dynamic int* x = (int*) malloc(10*sizeof(int)); Copyright ©: University of Illinois CS 241 Staff50 One is on the stack, one is on the heap Is there a difference?

Arrays int p[5]; p[0] p[1] p[2] p[3] p[4] Name of array (is a pointer) p Shorthand: *(p+1) is called p[1] *(p+2) is called p[2] etc.. Copyright ©: University of Illinois CS 241 Staff51

Example int y[4]; y[1]=6; y[2]=2; 6 2 y[0] y[1] y[2] y[3] y Copyright ©: University of Illinois CS 241 Staff52

Array Name as Pointer What’s the difference between the examples? Example 1: int z[8]; int *q; q=z; Example 2: int z[8]; int *q; q=&z[0]; Copyright ©: University of Illinois CS 241 Staff53

Array Name as Pointer What’s the difference between the examples? Example 1: int z[8]; int *q; q=z; Example 2: int z[8]; int *q; q=&z[0]; Copyright ©: University of Illinois CS 241 Staff54 NOTHING!! z (the array name) is a pointer to the beginning of the array, which is &z[0]

Questions What’s the difference between int* q; int q[5]; What’s wrong with int ptr[2]; ptr[1] = 1; ptr[2] = 2; Copyright ©: University of Illinois CS 241 Staff55

Questions 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]; Copyright ©: University of Illinois CS 241 Staff56 b[0]b[1]b[2] q

Questions 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]; Copyright ©: University of Illinois CS 241 Staff57 b[0]b[1]b[2] q *(q+1)

Questions 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]; Copyright ©: University of Illinois CS 241 Staff58 b[0]b[1]b[2] b*

Questions 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]; Copyright ©: University of Illinois CS 241 Staff59 b[0]b[1]b[2]

Questions 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]; Copyright ©: University of Illinois CS 241 Staff60

Strings Copyright ©: University of Illinois CS 241 Staff61

Strings (Null-terminated Arrays of Char) Strings are arrays that contain the string characters followed by a “Null” character ‘\0’ to indicate end of string.  Do not forget to leave room for the null character Example  char s[5]; s[0] s[1] s[2] s[3] s[4] s Copyright ©: University of Illinois CS 241 Staff62

Conventions Strings  “string”  “c” Characters  ‘c’  ‘X’ Copyright ©: University of Illinois CS 241 Staff63

String Operations strcpy strlen strcat strcmp Copyright ©: University of Illinois CS 241 Staff64

strcpy, strlen strcpy(ptr1, ptr2);  ptr1 and ptr2 are pointers to char value = strlen(ptr);  value is an integer  ptr is a pointer to char int len; char str[15]; strcpy (str, "Hello, world!"); len = strlen(str); Copyright ©: University of Illinois CS 241 Staff65

strcpy, strlen What’s wrong with char str[5]; strcpy (str, "Hello"); Copyright ©: University of Illinois CS 241 Staff66

strncpy strncpy(ptr1, ptr2, num);  ptr1 and ptr2 are pointers to char  num is the number of characters to be copied int len; char str1[15], str2[15]; strcpy (str1, "Hello, world!"); strncpy (str2, str1, 5); Copyright ©: University of Illinois CS 241 Staff67

strncpy strncpy(ptr1, ptr2, num);  ptr1 and ptr2 are pointers to char  num is the number of characters to be copied int len; char str1[15], str2[15]; strcpy (str1, "Hello, world!"); strncpy (str2, str1, 5); Caution: strncpy blindly copies the characters. It does not voluntarily append the string-terminating null character. Copyright ©: University of Illinois CS 241 Staff68

strcat strcat(ptr1, ptr2);  ptr1 and ptr2 are pointers to char Concatenates the two null terminated strings yielding one string (pointed to by ptr1). char S[25] = "world!"; char D[25] = "Hello, "; strcat(D, S); Copyright ©: University of Illinois CS 241 Staff69

strcat strcat(ptr1, ptr2);  ptr1 and ptr2 are pointers to char Concatenates the two null terminated strings yielding one string (pointed to by ptr1).  Find the end of the destination string  Append the source string to the end of the destination string  Add a NULL to new destination string Copyright ©: University of Illinois CS 241 Staff70

strcat Example What’s wrong with char S[25] = "world!"; strcat(“Hello, ”, S); Copyright ©: University of Illinois CS 241 Staff71

strcat Example What’s wrong with char *s = malloc(11 * sizeof(char)); /* Allocate enough memory for an array of 11 characters, enough to store a 10-char long string. */ strcat(s, "Hello"); strcat(s, "World"); Copyright ©: University of Illinois CS 241 Staff72

strcat strcat(ptr1, ptr2);  ptr1 and ptr2 are pointers to char Compare to Java and C++  string s = s + " World!"; What would you get in C?  If you did char* ptr0 = ptr1+ptr2;  You would get the sum of two memory locations! Copyright ©: University of Illinois CS 241 Staff73

strcmp diff = strcmp(ptr1, ptr2);  diff is an integer  ptr1 and ptr2 are pointers to char Returns  zero if strings are identical  < 0 if ptr1 is less than ptr2 (earlier in a dictionary)  > 0 if ptr1 is greater than ptr2 (later in a dictionary) int diff; char s1[25] = "pat"; char s2[25] = "pet"; diff = strcmp(s1, s2); Copyright ©: University of Illinois CS 241 Staff74

Can we make this work?! int x; printf("This class is %s.\n", &x); Copyright ©: University of Illinois CS 241 Staff75

Can we make this work?! int x; printf("This class is %s.\n", ); Copyright ©: University of Illinois CS 241 Staff76

Can we make this work?! int x; printf("This class is %s.\n", &x); (char*)&x Copyright ©: University of Illinois CS 241 Staff77

Can we make this work?! int x; printf("This class is %s.\n", &x); ((char*)&x)[0] = 'f'; 78Copyright ©: University of Illinois CS 241 Staff

Can we make this work?! int x; printf("This class is %s.\n", &x); ((char*)&x)[0] = 'f'; ((char*)&x)[1] = 'u'; ((char*)&x)[2] = 'n'; 79Copyright ©: University of Illinois CS 241 Staff

Can we make this work?! int x; printf("This class is %s.\n", &x); ((char*)&x)[0] = 'f'; ((char*)&x)[1] = 'u'; ((char*)&x)[2] = 'n'; ((char*)&x)[3] = '\0'; Perfectly legal and perfectly horrible! 80Copyright ©: University of Illinois CS 241 Staff

Can we make this work?! int x; printf("This class is %s.\n", &x); char* s = &x; strcpy(s, “fun”); 81Copyright ©: University of Illinois CS 241 Staff Perfectly legal and perfectly horrible!

Other operations Copyright ©: University of Illinois CS 241 Staff82

Increment & decrement x++: yield old value, add one ++x: add one, yield new value --x and x-- are similar (subtract one) int x = 10; x++; int y = x++; int z = ++x; Copyright ©: University of Illinois CS 241 Staff

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, z, w; y=10; w=2; x=y++; z=w--; Copyright ©: University of Illinois CS 241 Staff84 What are x and y at the end of each example?

Math: Increment and Decrement Operators Example 1: int x, y, z, w; y=10; w=2; x=++y; z=--w; First increment/ decrement, then assign result x is 11, z is 1 Example 2: int x, y, z, w; y=10; w=2; x=y++; z=w--; First assign result, then increment/ decrement x is 10, z is 2 Copyright ©: University of Illinois CS 241 Staff85

Math: Increment and Decrement Operators on Pointers  Example 1: int a[2]; int number1, number2, *p; a[0]=1; a[1]=10; p=a; number1 = *p++; number2 = *p;  What will number1 and number2 be at the end? Copyright ©: University of Illinois CS 241 Staff86

Math: Increment and Decrement Operators on Pointers  Example int a[2]; int number1, number2, *p; a[0]=1; a[1]=10; p=a; number1 = *p++; number2 = *p;  What will number1 and number2 be at the end? Hint: ++ increments pointer p not variable *p Copyright ©: University of Illinois CS 241 Staff87

Logic: Relational (Condition) Operators == equal to != not equal to > greater than < less than >= greater than or equal to <= less than or equal to Copyright ©: University of Illinois CS 241 Staff88

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.”); Perfectly LEGAL C statement! (syntactically speaking) It copies the value in b into a. The statement will be interpreted as TRUE if b is non-zero. Copyright ©: University of Illinois CS 241 Staff89

Review Copyright ©: University of Illinois CS 241 Staff90

Review int p1; What does &p1 mean? 91Copyright ©: University of Illinois CS 241 Staff

Review How much is y at the end? int y, x, *p; x = 20; *p = 10; y = x + *p; 92Copyright ©: University of Illinois CS 241 Staff

Review How much is y at the end? int y, x, *p; x = 20; *p = 10; y = x + *p; BAD!! Dereferencing an uninitialized pointer will likely segfault or overwrite something! Segfault = unauthorized memory access Copyright ©: University of Illinois CS 241 Staff93

Review What are the differences between x and y? char* f() { char *x; static char*y; return y; } Copyright ©: University of Illinois CS 241 Staff94

Review: Debugging if(strcmp("a","a")) printf("same!"); Copyright ©: University of Illinois CS 241 Staff95

Review: Debugging int i = 4; int *iptr; iptr = &i; *iptr = 5;//now i=5 Copyright ©: University of Illinois CS 241 Staff96

Review: Debugging char *p; p=(char*)malloc(99); strcpy("Hello",p); printf("%s World",p); free(p); Copyright ©: University of Illinois CS 241 Staff97

Review: Debugging char msg[5]; strcpy (msg,"Hello"); Copyright ©: University of Illinois CS 241 Staff98

OperatorDescriptionAssociativity () []. -> Parentheses (function call) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement left-to-right ! ~ (type) * & sizeof Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (change type) Dereference Address Determine size in bytes right-to-left * / %Multiplication/division/modulusleft-to-right + -Addition/subtractionleft-to-right >Bitwise shift left, Bitwise shift rightleft-to-right >= Relational less than/less than or equal to Relational greater than/greater than or equal to left-to-right == !=Relational is equal to/is not equal toleft-to-right &Bitwise AND left-to-right ^Bitwise exclusive ORleft-to-right |Bitwise inclusive ORleft-to-right &&Logical ANDleft-to-right ||Logical ORleft-to-right ?:Ternary conditionalright-to-left = += -= *= /= %= &= ^= |= >= Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment right-to-left,Comma (separate expressions)left-to-right