C Tutorial - Pointers CS 537 – Introduction to Operating Systems.

Slides:



Advertisements
Similar presentations
An introduction to pointers in c
Advertisements

David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming and Data Structure
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS Data Structures Chapter 4 Lists.
Pointers Applications
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
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.
Outline Midterm results Static variables Memory model
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Introduction to Data Structures Systems Programming.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers OVERVIEW.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Object-Oriented Programming in C++
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Introduction to Data Structures Systems Programming Concepts.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Lesson #8 Structures Linked Lists Command Line Arguments.
User-Written Functions
C Primer.
Day 03 Introduction to C.
C Programming Tutorial – Part I
Day 03 Introduction to C.
Dynamic Memory Allocation
Outline Defining and using Pointers Operations on pointers
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
Data Structures and Algorithms Introduction to Pointers
15213 C Primer 17 September 2002.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

C Tutorial - Pointers CS 537 – Introduction to Operating Systems

The Stack The stack is the place where all local variables are stored –a local variable is declared in some scope –Example int x; // creates the variable x on the stack As soon as the scope ends, all local variables declared in that scope end –the variable name and its space are gone –this happens implicitly – the user has no control over it

The Heap The heap is an area of memory that the user handles explicitly –user requests and releases the memory through system calls –if a user forgets to release memory, it doesn’t get destroyed it just uses up extra memory A user maintains a handle on memory allocated in the heap with a pointer

Pointers A pointer is simply a local variable that refers to a memory location on the heap Accessing the pointer, actually references the memory on the heap

Basic Idea pointer (on the stack) data (on the heap) 1200 starting address of data 1216 ending address of data 1200

Declaring Pointers Declaring a pointer is easy –declared like regular variable except that an asterisk (*) is placed in front of the variable –example int *x; –using this pointer now would be very dangerous x points to some random piece of data –declaring a variable does not allocate space on the heap for it it simply creates a local variable (on the stack) that will is a pointer use malloc() to actually request memory on the heap

malloc Prototype: int malloc(int size); –function searches heap for size contiguous free bytes –function returns the address of the first byte –programmers responsibility to not lose the pointer –programmers responsibility to not write into area past the last byte allocated Example: Memory Key previously allocated new allocation char *ptr; ptr = malloc(4); // new allocation ptr 10

free Prototype: int free(int ptr); –releases the area pointed to by ptr –ptr must not be null trying to free the same area twice will generate an error Example: initial memory Key allocated memory free memory free(ptr); p after free p2 2 2 p1 null

Using a Pointer To access a piece of data through a pointer, place an asterisk (*) before the pointer –example char *ptr = malloc(1); *ptr = ‘a’; if(*ptr == ‘a’) { … } Using the pointer without the asterisk actually accesses the pointer value –not the data the pointer is referencing –this is a very common mistake to make when trying to access data

sizeof() Function The sizeof() function is used to determine the size of any data type –prototype: int sizeof(data type); –returns how many bytes the data type needs for example: sizeof(int) = 4, sizeof(char) = 1 –works for standard data types and user defined data types (structures)

Simple Example int main() { 1 int x, y; 2 int *z; 3 z = malloc(sizeof(int)); 4 y = 5; 5 *z = 3; 6 x = *z + y; 7 free(z); return 0; } Stack Heap y x z

Simple Example 1.Declare local variables x and y. 2.Declare local pointer z. 3.Allocate space on the heap for single integer. This step also makes z point to that location (notice the address of the space on the heap is stored in z’s location on the stack. 4.Set the local variable y equal to 5. 5.Follow the pointer referenced by z to the heap and set that location equal to 3. 6.Grab the value stored in the local variable y and follow the pointer z to grab the value stored in the heap. Add these two together and store the result in the local variable x. 7.Releases the memory on the heap (so another process can use it) and sets the value in the z pointer variable equal to NULL. (this step is not shown on the diagram)

Common Mistakes Using a pointer before allocating heap space int *ptr; *ptr = 5; Changing the pointer, not the value it references int *ptr = malloc(sizeof(int)); ptr = 10; // sets value on stack to 10, not value on the heap Forgetting to free space on the heap (memory leak) int *p1 = malloc(sizeof(int)); int *p2 = malloc(sizeof(int)); p1 = p2; // making p1 point to p2 is fine, but now you can’t free // the space originally allocated to p1

Learning to Use Pointers DRAW PICTURES –when first using pointers it is much easier to draw pictures to learn what is happening –remember that an asterisk (*) follows the pointer –no asterisk (*) refers to the actual pointer variable on the stack

One More Example #include #define MAX_LINE 80 int main() { char *str = malloc(MAX_LINE * sizeof(char)); printf(“Enter your name: “); scanf(“%s”, str); printf(“Your name is: %s\n”, str); free(str); return 0; } str Stack Heap 12 Pat\0

One More Example 1.In one line, declare the pointer variable (gets placed on the stack), allocate memory on the heap, and set the value of the pointer variable equal to the starting address on the heap. 2.Read a value from the user into the space on the heap. This is why scanf takes pointers as the parameters passed in. 3.Release all the space on the stack pointed to by str and set the value of the str pointer on the stack equal to null. (step not shown)

Dereferencing Pointers work because they deal with addresses – not value –an operator performs an action at the value indicated by the pointer –the value in the pointer is an address We can find the value of any variable by dereferencing it –simply put an ampersand (&) in front of the variable and you now have the address of the variable

Revisiting scanf() Prototype: int scanf(char* str, void*, void*, …); What is void*? –void* is similar to object in Java –it can point at anything Since the data types being passed into scanf can be anything, we need to use void* pointers If you want to scan a value into a local variable, you need to pass the address of that variable –this is the reason for the ampersand (&) in front of the variable

scanf() Example #include #define MAX_LINE 80 int main() { char *student = malloc(char * sizeof(char)); int grade; printf(“Enter student’s name: “); scanf(“%s”, student); printf(“Enter student’s grade: “); scanf(“%d”, &grade); printf(“%s received a %d\n”, student, grade); free(student); return 0; }

scanf() Example Stack Heap grade student Pat\0 1

scanf() Example 1.In one line, declare the pointer variable (gets placed on the stack), allocate memory on the heap, and set the value of the pointer variable equal to the starting address on the heap. 2.Create the local variable grade on the heap. 3.Read a value from the user into the space on the heap – beginning at the address indicated by the pointer variable on the stack. 4.Read a value from the user into the address referred to by the address of grade. 5.Release all the space on the stack pointed to by student and set the value of the student pointer on the stack equal to null. (step not shown)

Pointers and Functions One limitation of functions is that they only return a single value So how to change multiple values in a single function? –pass in pointers –now any changes that are made are made to the address being referred to –this changes the value for the calling function as well as the called function

#include void swap(float*, float*); int main() { float *f1, *f2; f1 = malloc(sizeof(float)); f2 = malloc(sizeof(float)); printf(“Enter two numbers: “); scanf(“%f%f”, f1, f2); // assume the user types 23 and 19 printf(“f1 = %f\tf2 = %f\n”, *f1, *f2); swap(f1, f2); printf(“After swap: f1 = %f\tf2 = %f\n”, *f1, *f2); free(f1); free(f2); return 0; } void swap(float* first, float* second) { float tmp = *first; *first = *second; *second = tmp; }

Example Stack Heap f2 f main second first swap tmp

Example 1.Declare a pointer, f1, on stack. 2.Declare a pointer, f2, on stack. 3.Allocate space on the heap for a float and place the address in the pointer variable f1. 4.Allocate space on the heap for a float and place the address in the pointer variable f2. 5.Read values from the user. Hand scanf() the pointers f1 and f2 and the data gets put on the heap. 6.Call the swap function. This pushes a new entry in the stack. Copy the value of the pointers f1 and f2 into first and second. 7.Create a new local variable tmp. Follow the pointer of first and place its value into temp. 8.Follow the pointer of second, grab the value, follow the pointer of first, place grabbed value there. 9.Grab the value from tmp, follow the pointer of second, place the grabbed value there.

Lists Remember structures? –structures together with pointers can be used to make a list Some of the data in a structure will contain the information being stored One of the fields in the structure will be a pointer to the next structure in the list

Lists Example of a structure used in a linked list struct list_node { char letter; struct list_node *next; } The letter variable is the data to be stored The next variable will point at the next element in the list –or NULL if there are no more elements

Lists struct list_node letter next A struct list_node letter next M struct list_node letter next W

#include typedef struct list_node { char word[20]; struct list_node* next; } list_node; int main() { list_node* head = NULL; char str[20]; printf(“Enter a word: “); scanf(“%s”, str); while(str[0] != ‘\n’) { list_node* tmp = (list_node*)malloc(sizeof(list_node)); strcpy(tmp->word, str); if(head) { tmp->next = tmp; } else { tmp->next = NULL; } head = tmp; printf(“Enter a word: “); scanf(“%s”, str); } return 0; }

Example Stage 0: empty list head Stage 1: one element in list struct list_node word next hi Stage 2: multiple elements in list struct list_node word next hi struct list_node word next at head

2-D Pointers To really make things confusing, you can have pointers to pointers –and pointers to pointers to pointers … This comes in handy whenever a 2-D array is needed –you can also declare 2-D arrays, but these go on the stack –if dynamic memory is needed, must use pointers Declaring a pointer to a pointer –just put 2 asterisks (*) in front of the variable –example char **names;

2-D Pointers Basic idea twoD

argv Up until now, main has been written –int main() { … } This is okay, but it’s usually written –int main(int argc, char** argv) { … } argc –number of command line arguments being passed in this counts the name of the program argv –this is an array of strings – a 2-D character array –each string represents one command line argument

Example #include int main(int argc, char** argv) { int i; printf(“Number of arguments: %d\n”, argc); for(i=0; i<argc; i++) printf(“argument %d: %s”, i, argv[i]); return 0; }

Example Given the following command line prompt> example –o option required The output of the sample program Number of arguments: 4 argument 0: example argument 1: -o argument 2: option argument 3: required

Example Stack Heap argv argc i example -o option required

Creating a 2-D Array Assume a 2-D array of characters is needed –this is basically an array of strings Assume 4 strings with a max of 80 chars int main() { char** names; int i; names = (char**)malloc(4 * sizeof(char*)); for(i=0; i<4; i++) names[i] = (char*)malloc(80 * sizeof(char)); for(i=0; i<4; i++) free(names[i]); free(names); return 0; }

2-D Arrays Once you really understand this previous example, you are well on your way to understanding pointers Let’s take a closer look at exactly what is going on

2-D Arrays Stack Heap names i 0X123XXX 80 chars wide 1324

2-D Arrays 1.Create a pointer on the stack that will point to a group of pointers 2.Create a local variable on the stack 3.Make names point to an array of 5 pointers to characters. This array is located on the heap. 4.Go through each pointer in the array and make it point at an 80 character array. Each of these 80 character arrays is also located on the heap 5.Freeing each of the 80 character arrays. (not shown on diagram). 6.Free the array of pointers. (not shown on the diagram)