Introduction to Systems Programming - COMP 1002, 1402

Similar documents
arrays C Programming Language - Arrays

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

The C Programming Language course syllabus associate level

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

1 Abstract Data Types Information Hiding

Sources: On the Web: Slides will be available on:

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Informatica e Sistemi in Tempo Reale

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Object Oriented Software Design II

C++FA 5.1 PRACTICE MID-TERM EXAM

5 Arrays and Pointers

IC4 Programmer s Manual

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Chapter 13 Storage classes

C++ INTERVIEW QUESTIONS

CP Lab 2: Writing programs for simple arithmetic problems

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

Semantic Analysis: Types and Type Checking

Lecture 12 Doubly Linked Lists (with Recursion)

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Object Oriented Software Design II

6.S096 Lecture 1 Introduction to C

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Chapter 7D The Java Virtual Machine

ECS 165B: Database System Implementa6on Lecture 2

Object Oriented Software Design II

C Interview Questions

MISRA-C:2012 Standards Model Summary for C / C++

Data Structure with C

Stack Allocation. Run-Time Data Structures. Static Structures

Introduction to Information Security

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Comp151. Definitions & Declarations

Stacks. Linear data structures

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25

X86-64 Architecture Guide

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers

Adding Alignment Support to the C++ Programming Language / Wording

The programming language C. sws1 1

Tutorial on C Language Programming

Objective-C Tutorial

Chapter 5 Names, Bindings, Type Checking, and Scopes

Programming languages C

Bonus ChapteR. Objective-C

Habanero Extreme Scale Software Research Project

C++ Programming Language

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

What is COM/DCOM. Distributed Object Systems 4 COM/DCOM. COM vs Corba 1. COM vs. Corba 2. Multiple inheritance vs multiple interfaces

ECE 0142 Computer Organization. Lecture 3 Floating Point Representations

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference.

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Module 816. File Management in C. M. Campbell 1993 Deakin University

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

C++ Overloading, Constructors, Assignment operator

Data Structures using OOP C++ Lecture 1

How To Write Portable Programs In C

/* File: blkcopy.c. size_t n

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

7.1 Our Current Model

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Static Code Analysis Procedures in the Development Cycle

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Today. Binary addition Representing negative numbers. Andrew H. Fagg: Embedded Real- Time Systems: Binary Arithmetic

C++FA 3.1 OPTIMIZING C++

Java Interview Questions and Answers

Applying Clang Static Analyzer to Linux Kernel

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Common Data Structures

ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP,

picojava TM : A Hardware Implementation of the Java Virtual Machine

Java from a C perspective. Plan

Crash Course in Java

C Programming Tutorial

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Keil C51 Cross Compiler

In this Chapter you ll learn:

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Transcription:

POINTERS Introduction to Systems Programming - COMP 1002, 1402

Outline Memory Allocation Pointers in C Pointer and addresses Pointer Arithmetic Dynamic Memory Allocation

Memory Allocation When you declare a variable, some memory is allocated to store the value of the variable. When you declare a global variable, the memory that is allocated for the global variable is permanent throughout the program. When you declare a local variable inside a function, then the memory allocated for the local variable exists in a part of memory called the stack, and it exists only for as long as the function is being called. Same for parameters to a function.

Declaring Pointers in C 4 int *p; a pointer to an int double *q; a pointer to a double char **r; type *s; a pointer to a pointer to a char a pointer to an object of type type E.g, a struct, union, function, something defined by a typedef, etc.

Declaring Pointers in C (continued) 5 Pointer declarations: read from right to left const int *p; p is a pointer to an integer constant I.e., pointer can change, thing it points to cannot int * const q; q is a constant pointer to an integer variable I.e., pointer cannot change, thing it points to can! const int * const r; r is a constant pointer to an integer constant

Pointers in C 6 Used everywhere For building useful, interesting, data structures For returning data from functions For managing arrays '&' unary operator generates a pointer to x E.g., scanf("%d", &x); E.g., p = &c; Operand of '&' must be an l-value i.e., a legal object on left of assignment operator ('=') Unary '*' operator dereferences a pointer i.e., gets value pointed to E.g. *p refers to value of c (above) E.g., *p = x + y; *p = *q;

Pointers and Addresses C allows you to get the address of a variable. C has a type called pointer that points to another type, such as int, unsigned char, float etc. So, in C, there is an int pointer, unsigned char pointer etc. A pointer to an integer is used to contain the address of an integer. int n; // declare an integer variable called n int * iptr; // declare a variable called iptr // this variable is a pointer to an integer void func() { iptr = &n; // set the value of iptr to the address of variable n

Pointer and Address Example Here, we show the address and content of the variables n and iptr as they are declared. After calling the function, the content at Address 101 will be the value 100. Variable Address Content n 100 20 iptr 101 0 100 int n = 20; // declare an integer variable called n int * iptr = 0; // declare a variable called iptr // this variable is a pointer to an integer void func() { iptr = &n; // set the value of iptr to the address of variable n

The & Operator As you saw in the preceding slide, the & operator is used to get the address of a variable. Here are some more examples. int n = 20; int * iptr = 0; float f = 1.05; float * fptr = &f; Variable Address Content n 100 20 iptr 101 0 100 f 102 1.05 fptr 103 102 void func() { iptr = &n; // set the value of iptr to the address of variable n

The * Operator: Dereferencing a Pointer You can get the contents of what the pointer is pointing to by dereferencing a pointer. int n = 20; int * iptr = 0; int i; void func() { iptr = &n; i = *iptr + 50;

Exercise: What gets printed? Address 200 201 202 203 204 204 int i; #include <stdio.h> int n = 20; float f = 1.05; float * fptr = &f; int * iptr = 0; int i; int main() { iptr = &n; printf("addresses %d %d\n", iptr, fptr); printf("values %d %f\n", *iptr, *fptr); i = *iptr + 50; *iptr = 10; printf("values %d %d\n", n, i); return 0;

Dereferencing Pointer Dereferencing pointer actually refers to the contents of what the pointer is pointing to. This doesn t simply refer to the value. Hence, the content can be changed! #include <stdio.h> int n = 20; int * iptr = 0; int main() { iptr = &n; *iptr = 10; printf("values %d\n", n); return 0;

Call by Pointer Contrast the following functions One is call by value, the other is call by pointer. What exactly happens when those functions are called? #include <stdio.h> int n = 20; void func1(int i) { i = i + 10; void func2(int *r) { *r = *r + 20; int main() { func1(n); printf( n is %d\n", n); func2(&n); printf( n is %d\n", n); return 0;

Can pointer refer to invalid address? Yes, you can set pointer to any value you want. But, if you set it to some reserved address, then the program will crash when you re trying to refer to the reserved address. int i; int *iptr; int main() { iptr = (int *)500; i = *iptr + 50; Set to invalid address 500 (probably reserved by the operating system) Program crashes when trying to reference invalid address.

Pointer Arithmetic 15 int *p, *q; q = p + 1; Construct a pointer to the next integer after *p and assign it to q double *p, *r; int n; r = p + n; Construct a pointer to a double that is n doubles beyond *p, and assign it to r n may be negative

Pointer Arithmetic (continued) 16 long int *p, *q; p++; q--; Increment p to point to the next long int; decrement q to point to the previous long int float *p, *q; int n; n = p q; n is the number of floats between *p and *q; i.e., what would be added to q to get p

Pointer Arithmetic (continued) 17 long int *p, *q; p++; q--; Increment p to point to the next long int; decrement q to point to the previous long int float *p, *q; int n; n = p q; n is the number of floats between *p and *q; i.e., what would be added to q to get p

The new function void func( ) { int *iptr; iptr = new int(15); Refer to the highlighted line above. The new function does the following: Allocate memory in the part of memory called heap. The amount of memory allocated is the amount needed to contain one integer. The content of the memory location is set to the integer 15. new returns the address of the memory that has just been allocated.

The delete function The delete function frees the memory that has been created by new. Traditionally, C uses the functions malloc and free, but I don t like them. These days, we use the functions new and delete because they are cleaner. void func( ) { int *iptr; iptr = new int(15); delete iptr; iptr = new int(20);

malloc and free void * malloc ( size_t size ); void free ( void * ptr ); malloc requests some memory from the Operation System and returns the address of the memory allocated. free frees up the space previously received by malloc. void func(int n) { int i; int *iptr; iptr = (int *)malloc(n*sizeof(int)); for (i=0;i<n;i++) { iptr[i] = 15 + i * 2; free(iptr);

Pointer Example Program: Normalize (Part 1) Example: The normalize function to normalize a vector Mathematical background: Given a 3D vector V = (x,y,z), the magnitude of the vector V is sqrt(x*x+y*y+z*z) Normalizing a vector means to make the vector the same direction as before, but with unit length (that is, the magnitude of the normalized vector should be 1). void Normalize(float *x, float *y, float *z) { float mag; mag = (*x) * (*x) + (*y) * (*y) + (*z) * (*z); mag = sqrt(mag); // at the beginning of source file, need #include <math.h> // to use the function sqrt *x = (*x) / mag; *y = (*y) / mag; *z = (*z) / mag;

Pointer Example Program: Normalize (Part 2) Here, we use the Normalize function to change the values of a, b, c. The Normalize function can be used to change the values of other variables. This is a good use of pointers as parameters, because they can change the values of the contents they refer to. int main() { float a, b, c; a = 10.0; b = 20.0; c = 15.0; Normalize(&a, &b, &c); printf( vector is %f %f %f\n, a, b, c); return 0;

The NULL Pointer malloc returns the address of the memory that has been allocated. However, sometimes it fails. For example, when the heap is full, or when malloc requests too much memory, the OS cannot give malloc the memory. In this case, the return value of malloc is the NULL pointer. void func(int n) { void func(int n) { int i; int *iptr; iptr = (int *)malloc(n*sizeof(int)); if (iptr!= 0) { // check that malloc did not return the NULL pointer for (i=0;i<n;i++) { iptr[i] = 15 + i * 2; free(iptr);

What is the relationship between array and pointer? 24 Arrays and pointers are closely related in C In fact, they are essentially the same thing! Esp. when used as parameters of functions int A[10]; int *p; Type of A is int * p = A; and A = p; are legal assignments *p refers to A[0] *(p + n) refers to A[n] p = &A[5]; is the same as p = A + 5;

Arrays and Pointers (continued) 25 double A[10]; vs. double *A; Only difference: double A[10] sets aside ten units of memory, each large enough to hold a double, and A is initialized to point to the zeroth unit. double *A sets aside one pointer-sized unit of memory, not initialized You are expected to come up with the memory elsewhere! Note: all pointer variables are the same size in any given machine architecture Regardless of what types they point to

Array and Address When you declare an array, the name of the array also refers to the address of its first element. In the following example, the value of n is the same as the value of &(n[0]) int n[20]; // declare an array of 20 integers void func() { if (n==&(n[0])) { printf( they are the same\n );

Array and Pointer Since the name of an array is the same as an address, and a pointer is also the same as an address, a pointer can be set to an array. However, do not set array to pointer. int n[20]; // declare an array of 20 integers int *iptr; void func() { iptr = n; // set pointer to array n[0] = 5; printf( %d, *iptr); // n = iptr; // do not set array to pointer

Treating Pointer as Array int n[20]; // declare an array of 20 integers int *iptr; void func() { iptr = n; // set pointer to array for (i=0;i<20;i++) { iptr[i] = 5; // treat pointer as array for (i=0;i<20;i++) { printf( %d, n[i]);

Example: Average float fg[80]; float GetAverage(float *marray, int len) { int i; float sum; sum = 0; for (i=0;i<len;i++) { sum += marray[i]; return sum/(float)len; int main( ) { float f1[120]; float f2[60]; float a, b, c; // some code to set the values of f1, f2 and fg a = GetAverage(f1,120); b = GetAverage(f2,60); c = GetAverage(fg,80); return 0;

new and delete for Arrays We learned that new can be used to allocate space for an int, float etc. We learned that delete is used to free the space. Now, new can be used to allocate an entire array, and delete is used to free the entire array. void func() { int *iptr; iptr = new int[20]; delete [ ] iptr;

Example: Creating a new array // print 1! up to n! 2000 times void printfactorials(int n) { int *iptr; int i, j; iptr = new int[n]; // create an array of length n iptr[0] = 1; for (i=1;i<n;i++) { iptr[i] = iptr[i-1] * (i+1); // set each element of the array for (i=0;i<2000;i++) { for (j=0;j<n;j++) { printf( %d, iptr[j]); printf( \n ); delete [ ] iptr; // free the memory

Exercise: Delete Duplicates Write a function DeleteDuplicates This function receives an array arr as an argument, and an integer len, that tells the length of the array. The array received as argument has been allocated by new. The argument array contains floating point numbers in non-decreasing order. DeleteDuplicates should create a new array, except that this array should contain no duplicates. DeleteDuplicates should return the address of this new array. DeleteDuplicates should free the memory used by the old array. The length of the new array is set in nlen. float *DeleteDuplicates(float *arr, int len, int *nlen); // function declaration void func() { // example of use float *eptr; int nlen; eptr = new float[5]; eptr[0] = 1.0; eptr[1] = 1.6; eptr[2] = 1.6; eptr[3] = 2.3; eptr[4] = 2.3; eptr = DeleteDuplicates(eptr,5, &nlen);

Note 33 C does not assign arrays to each other E.g, double A[10]; double B[10]; A = B; assigns the pointer value B to the pointer value A Original contents of array A are untouched (and possibly unreachable!)

Arrays as Function Parameters 34 void init(float A[], int arraysize); void init(float *A, int arraysize); Are identical function prototypes! Pointer is passed by value I.e. caller copies the value of a pointer to float into the parameter A Called function can reference through that pointer to reach thing pointed to

Arrays as Function Parameters (continued) 35 void init(float A[], int arraysize){ int n; for(n = 0; n < arraysize; n++) A[n] = (float)n; //init Assigns values to the array A in place So that caller can see the changes!

Examples 36 while ((rc = scanf("%lf", &array[count]))!=eof && rc!=0) double getlargest(const double A[], const int sizea) { double d; if (sizea > 0) { d = getlargest(&a[1], sizea-1); return (d > A[0])? d : A[0]; else return A[0]; // getlargest

Result 37 Even though all arguments are passed by value to functions pointers allow functions to assign back to data of caller Arrays are pointers passed by value

Exercise: Reverse There is an array of integers int a[100]; Assume that the array contains some numbers. Reverse the array. In other words, after you run your code, the first element should contain the last element, and vice versa. And, the second element should contain the next to last element etc. int a[100]; int main() { Fill in code here

Exercise: Change Write a function CalculateChange(int m) that prints the change for a money value. For example CalculateChange(115) should print 25 25 25 25 10 5 The valid coin values are 1, 5, 10 and 25.

Review: Pointers What does the following program print? #include <stdio.h> Memory: int main() { int i, j; Variable Address Content int *iptr; i 1000? j 1001? i = 256; iptr 5000? iptr = &i; printf( %d, (int)iptr); printf( %d, *iptr); iptr = (int *)i; printf( %d, (int)iptr); return 0;

Review: Pointers Answer of previous page: 1000 256 256 Which line(s) may cause compile time error? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <stdio.h> int main() { int i, j; int *iptr; i = 256; iptr = 512; iptr = &i; iptr = (int *)i; *iptr = 20; j = iptr; j = &iptr; j = (int) &iptr; &i = iptr; return 0;

Review: Pointers Answer of previous page: Lines 7, 13, 14 and 17 Which line(s) may cause the program to crash at runtime? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <stdio.h> int main() { int i, j; int *iptr; int *jptr; i = 256; iptr = (int *)512; jptr = iptr; i = *iptr + 10; iptr = (int *)i; *iptr = 20; return 0;

Review: new and delete Answer of previous page: Lines 12 and 15 Which line(s) may cause compile time error? Which line(s) may cause program to crash at run time? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include <stdio.h> int main() { int i; int *iptr; i = 10; iptr = new int(5); *iptr = 20; delete iptr; *iptr = 15; iptr = &i; delete iptr; return 0; Answer : Line 13 may cause a problem because you write to memory that has been freed. Line 16 has an error because you try to free memory from the stack, i.e. not created by new.

QUESTIONS? 44