Pointers and Dynamic Memory Allocation

Similar documents
Pointers, Dynamic Data, and Reference Types

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Pointers! Arizona State University 1

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018


CSC 211 Intermediate Programming. Arrays & Pointers

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

6. Pointers, Structs, and Arrays. 1. Juli 2011

CS201- Introduction to Programming Current Quizzes

What is an algorithm?

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Dynamic Memory Allocation

Pointers and References

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Exam 3 Chapters 7 & 9

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

[0569] p 0318 garbage

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Homework #3 CS2255 Fall 2012

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

CA31-1K DIS. Pointers. TA: You Lu

Memory and C++ Pointers

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Chapter 2. Procedural Programming

CS201 Some Important Definitions

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

CS 161 Exam II Winter 2018 FORM 1

C10: Garbage Collection and Constructors

COMP6771 Advanced C++ Programming

Object-Oriented Principles and Practice / C++

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Variation of Pointers

by Pearson Education, Inc. All Rights Reserved.

Introduction to Computer Science Midterm 3 Fall, Points

Propedéutico de Programación

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

FORM 2 (Please put your name and form # on the scantron!!!!)

Come and join us at WebLyceum

C11: Garbage Collection and Constructors

CPSC 427: Object-Oriented Programming

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

CPSC 427a: Object-Oriented Programming

Dynamic Allocation of Memory

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Scope. Scope is such an important thing that we ll review what we know about scope now:

CSE 100: C++ TEMPLATES AND ITERATORS

Object Oriented Design

Pointers and Terminal Control

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Procedural programming with C

Short Notes of CS201

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

a data type is Types

CS201 - Introduction to Programming Glossary By

What have we learned about when we learned about function parameters? 1-1

CPSC 427: Object-Oriented Programming

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

CSCI 171 Chapter Outlines

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

C Pointers. 6th April 2017 Giulio Picierro

For Teacher's Use Only Q No Total Q No Q No

Lecture 9. Pointer, linked node, linked list TDDD86: DALP. Content. Contents Pointer and linked node. 1.1 Introduction. 1.

Object-Oriented Programming for Scientific Computing

Launchpad Lecture -10

Language comparison. C has pointers. Java has references. C++ has pointers and references

CPSC 427: Object-Oriented Programming

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Variables, Memory and Pointers

The PCAT Programming Language Reference Manual

CS 11 C track: lecture 5

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Constants, References

Memory Allocation in C

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Introducing C++ to Java Programmers

C++ for Java Programmers

Transcription:

Pointers and Dynamic Memory Allocation ALGORITHMS & DATA STRUCTURES 9 TH SEPTEMBER 2014

Last week Introduction This is not a course about programming: It s is about puzzling. well.. Donald Knuth Science is what we understand well enough to explain to a computer. Beware of bugs in the above code; I have only proved it correct, not tried it. 2

Algorithm Algorithm = Human (high-level) way of teaching a computer what to do to solve a problem An algorithm is a welldefined procedure which takes an input value and returns an output value 3

C++ Very powerful Bizarre syntax But this is NOT a C++ course. 4

Pointers Pointers Powerful feature of C++ One of the most difficult to master Essential for construction of interesting (recursive) data structures, e.g. lists and trees. 5

Addresses and Pointers owhen we declare a variable some memory is allocated for it. The memory location can be referenced through the identifier of the variable. othus, we have two properties for any variable : its address and its data value. othe address of the variable can be accessed through the referencing operator &. &i gives the memory location where the data value for i is stored oaddresses can be displayed, e.g., by using cout o Addresses displayed in HEXADECIMAL 6

Example #include <iostream.h> void main( ) { int data = 100; float value = 56.47; cout << data << &data << endl; cout << value << &value << endl; } value data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 56.47 100 Output: 100 FFF4 56.47 FFF0 7

Pointer Variables The pointer data type Each address has a type, which depends on the (type of the) variable it belongs to. Suppose we have declare the variable int v; Then the type of v s address is int * pronounced as pointer-to-int or integer pointer We can also declare variables that have addresses as values. For example, a variable p holding an integer pointer is declared as int *p; 8

Declaration of Pointer Variables A pointer variable is declared by: datatype *pointervarname; The pointer variable pointervarname is used to point to a variable with a value of type datatype The * before the pointervarname indicates that this is a pointer variable, not a regular variable The * is not a part of the pointer variable name 9

Declaration of Pointer Variables (Cont..) Example int *ptr1; float *ptr2; ptr1 is a pointer to an int variable i.e., it can have the address of the memory location allocated to an int value ptr2 is a pointer to a float variable i.e., it can have the address of the memory location allocated to a float value 10

Declaration of Pointer Variables (Cont..) Whitespace doesn t matter and each of the following will declare ptr as a pointer (to a float) variable and data as a float variable float *ptr, data; float* ptr, data; float (*ptr), data; float data, *ptr; 11

Assignment of Pointer Variables A pointer variable has to be assigned a valid memory address (initialized) before it can be used in the program Example: float data = 50.8; float *ptr; ptr = &data; This will assign the address of the memory location allocated for the floating point variable data to the pointer variable ptr. This is OK, since the variable data has already been allocated some memory space having a valid address 12

Assignment of Pointer Variables (Cont..) FFF0 float data = 50.8; float *ptr; FFF1 FFF2 FFF3 ptr = &data; data FFF4 50.8 FFF5 FFF6 13

Assignment of Pointer Variables (Cont..) ptr FFF0 float data = 50.8; float *ptr; FFF1 FFF2 FFF3 ptr = &data; data FFF4 50.8 FFF5 FFF6 14

Assignment of Pointer Variables (Cont..) ptr FFF0 FFF4 FFF1 float data = 50.8; FFF2 float *ptr; FFF3 ptr = &data; data FFF4 50.8 FFF5 FFF6 15

Assignment of Pointer Variables (Cont..) Don t try to assign a specific integer value to a pointer variable since it can be disastrous float *ptr; ptr = 120; You cannot assign the address of one type of variable to a pointer variable of another type even though they are both integrals int data = 50; float *ptr; ptr = &data; 16

Initializing pointers A pointer can be initialized during declaration by assigning it the address of an existing variable float data = 50.8; float *ptr = &data; If a pointer is not initialized during declaration, it is wise to give it a NULL (or nullptr in C+11) value int *ip = 0; float *fp = nullptr; 17

The NULL pointer The NULL pointer is a valid address for any (pointer) data type. But NULL is not memory address 0. It is used to indicate that the pointer does not refer to a variable. It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer s job to check for this. 18

Dereferencing Dereferencing Using a pointer variable to access the value stored at the location pointed by the variable Provide indirect access to values and also called indirection Done by using the dereferencing operator * in front of a pointer variable Unary operator Highest precedence 19

Dereferencing (Cont..) Example: float data = 50.8; float *ptr; ptr = &data; cout << *ptr; Once the pointer variable ptr has been declared, *ptr represents the object pointed to by ptr (or the value located at the address specified by ptr) and may be treated like any other variable of float type 20

Dereferencing (Cont..) The dereferencing operator * can also be used in assignments. *ptr = 200; Make sure that ptr has been properly initialized 21

Dereferencing Example #include <iostream.h> void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } ptr data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF4 50.8 Output: 22

Dereferencing Example (Cont..) #include <iostream.h> void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; }utput: ptr data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF4 50.8 FFF4 50.80 23

Dereferencing Example (Cont..) #include <iostream.h> void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } ptr data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF4 27.4 Output: 24

Dereferencing Example (Cont..) #include <iostream.h> void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } Output: 27.4 ptr data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF4 27.4 25

Dereferencing Example (Cont..) #include <iostream.h> void main() { float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl; } ptr data FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF4 27.4 Output:27.4 26

Operations on Pointer Variables Assignment the value of one pointer variable can be assigned to another pointer variable of the same type Relational operations - two pointer variables of the same type can be compared for equality, and so on Some limited arithmetic operations integer values can be added to and subtracted from a pointer variable value of one pointer variable can be subtracted from another pointer variable 27

const Pointer Variables Two possibilities 1. the variable itself is a constant the pointer value cannot be changed; int v = 42; int * const q = &v; 2. the object to which it refers is (treated as) a constant. int v = 42; const int *p = &v; 28

Pointers to arrays A pointer variable can be used to access the elements of an array of the same type. int gradelist[8] = {92,85,75,88,79,54,34,96}; int * mygrades = gradelist; cout << gradelist[1]; cout << *mygrades; cout << *(mygrades + 2); cout << mygrades[3]; Initially mygrades refers to the first element of gradelist. Note that the array name gradelist acts like the pointer variable mygrades. 29

Dynamic Memory Allocation 30

Types of Program Data Static Data: Memory allocation exists throughout execution of program Automatic Data: Automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function Dynamic Data: Explicitly allocated and deallocated during program execution by C++ instructions written by programmer 31

Allocation of Memory Static Allocation: Allocation of memory space at compile time. Dynamic Allocation: Allocation of memory space at run time. 32

Scope (revisited) Scope refers to the visibility of variables. In other words, which parts of your program can see or use it. A local variable is limited in scope to all the code below the declaration until the end of the enclosing block. function arguments are local for-loop: scope is heading + body global variables are not limited in scope. Their visibility is throughout the entire program after declaration 33

Dynamic memory allocation Dynamic allocation is useful when arrays need to be created whose size is not known until run time complex structures of unknown size and/or shape need to be constructed as the program runs objects need to be created and the constructor arguments are not known until run time 34

Dynamic memory allocation Pointers need to be used for dynamic allocation of memory Use the operator new to dynamically allocate space Use the operator delete to later free this space 35

The new operator If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. If sufficient memory is not available, the new operator returns NULL. The dynamically allocated object/array exists until the delete operator destroys it. 36

The delete operator The delete operator deallocates the object or array currently pointed to by the pointer which was previously allocated at run-time by the new operator. the freed memory space is returned to Heap the pointer is then considered unassigned If the value of the pointer is NULL there is no effect. 37

Example int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr = NULL; ptr FDE0 FDE1 FDE2 FDE3 0EC4 0EC5 0EC6 0EC7 38

Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr FDE0 FDE1 FDE2 FDE3 0EC4 ptr = NULL; 0EC4 0EC5 0EC6 0EC7 39

Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr FDE0 FDE1 FDE2 FDE3 0EC4 ptr = NULL; 0EC4 22 0EC5 0EC6 0EC7 40

Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr FDE0 FDE1 FDE2 FDE3 0EC4 ptr = NULL; Output: 22 0EC4 0EC5 0EC6 22 0EC7 41

Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr FDE0 FDE1 FDE2 FDE3? ptr = NULL; 0EC4 0EC5 0EC6 0EC7 42

Example (Cont..) int *ptr; ptr = new int; *ptr = 22; cout << *ptr << endl; delete ptr; ptr FDE0 FDE1 FDE2 FDE3 0 ptr = NULL; 0EC4 0EC5 0EC6 0EC7 43

Dynamic allocation and deallocation of arrays Use the new[intexp] to create an array of objects instead of a single instance. On the delete statement use [] to indicate that an array of objects is to be deallocated. 44

Example of dynamic array allocation int* grades = NULL; int numberofgrades; cout << "Enter the number of grades: "; cin >> numberofgrades; grades = new int[numberofgrades]; for (int i = 0; i < numberofgrades; i++) cin >> grades[i]; for (int j = 0; j < numberofgrades; j++) cout << grades[j] << " "; delete [] grades; grades = NULL; 45

Dynamic allocation of 2D arrays A two dimensional array is really an array of arrays (rows). To dynamically declare a two dimensional array of int type, you need to declare a pointer to a pointer as: int **matrix; 46

Dynamic allocation of 2D arrays (Cont..) To allocate space for the 2D array with r rows and c columns: You first allocate the array of pointers which will point to the arrays (rows) matrix = new int*[r]; This creates space for r addresses; each being a pointer to an int (array). Then you need to allocate the space for the 1D arrays themselves, each with a size of c for(i=0; i<r; i++) matrix[i] = new int[c]; 47

Dynamic allocation of 2D arrays (Cont..) The elements of the array matrix now can be accessed by the matrix[i][j] notation Keep in mind, the entire array is not in contiguous space (unlike a static 2D array) The elements of each row are in contiguous space, but the rows themselves are not. matrix[i][j+1] is after matrix[i][j] in memory, but matrix[i][0] may be before or after matrix[i+1][0] in memory 48

Example: Binomial Coefficients binomial coefficient: 1 1 1 k n k n k n Pascal s Identity 1 0 n n n )!!(! n-k k n k n 35 24 6 5040 3!(4)! 7! 3 7

Binomial coefficients in C++ int choose (int n, int k) { } if (k == 0 k == n) { return 1; } else { } return choose(n-1,k-1) + choose(n-1,k); Double recursion: (very) inefficient!

Efficient solution using arrays int **binomial; void PascalsTriangle (int N) { } binomial = new int *[N+1]; for (int n = 0; n <= N; n++) { } binomial[n] = new int [n+1]; binomial[n][0] = 1; binomial[n][n] = 1; for (int k = 1; k < n; k++) { } Dynamic programming binomial[n][k] = binomial[n-1][k-1] + binomial[n-1][k];

Passing pointers to a function 52

Pointers as arguments to functions Pointers can be passed to functions just like other types. Just as with any other argument, verify that the number and type of arguments in function invocation match the prototype (and function header). 53

Example of pointer arguments void Swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(&x,&y); // passes addresses of x and y explicitly cout << x << " " << y << endl; } 54

Example of reference arguments void Swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main () { int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(x,y); // passes addresses of x and y implicitly cout << x << " " << y << endl; } References are like pointer constants with implicit (de)referencing. 55

More example void main () { int r, s = 5, t = 6; int *tp = &t; r = MyFunction(tp,s); r = MyFunction(&t,s); r = MyFunction(&s,*tp); } int MyFunction(int *p, int i) { *p = 3; i = 4; return i; } 56

Memory leaks and Dangling Pointers 57

Memory leaks When you dynamically create objects, you can access them through the pointer which is assigned by the new operator Reassigning a pointer without deleting the memory it pointed to previously is called a memory leak It results in loss of available memory space 58

Memory leak example int *ptr1 = new int; int *ptr2 = new int; *ptr1 = 8; *ptr2 = 5; ptr2 = ptr1; ptr1 ptr2 8 5 How to avoid? ptr1 ptr2 8 5 59

Inaccessible object An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it. It is a logical error and causes memory leaks. 60

Dangling Pointers Is a pointer that points to memory allocations that have been deallocated local objects whereof the scope has ended dynamically allocated objects that have been deleted explicitly 61

Dangling Pointer example int *answer ( ) { int result = 6*7; return &result; } void main ( ) { int *ptr = answer ( ); cout << " answer = " << *ptr; } 62

Dangling Pointer example 2 int *ptr1 = new int; int *ptr2; *ptr1 = 8; ptr2 = ptr1; delete ptr1; ptr1 ptr2 ptr1 8 How to avoid? ptr2 63

Pointers to objects

Pointers to (composite) objects Any type that can be used to declare a variable/object can also have a pointer type. Consider the following class: class Rational { private: int numerator; int denominator; public: Rational(int n, int d); void Display(); }; 65

Pointers to objects (Cont..) Rational *rp = NULL; Rational r(3,4); rp = &r; rp FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD 0 66

Pointers to objects (Cont..) Rational *rp = NULL; Rational r(3,4); rp = &r; numerator = 3 denominator = 4 r rp FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD 0 3 4 67

Pointers to objects (Cont..) Rational *rp = NULL; Rational r(3,4); rp = &r; numerator = 3 denominator = 4 r rp FFF0 FFF1 FFF2 FFF3 FFF4 FFF5 FFF6 FFF7 FFF8 FFF9 FFFA FFFB FFFC FFFD FFF4 3 4 68

Pointers to objects (Cont..) If rp is a pointer to an object, then two notations can be used to reference the instance/object rp points to. Using the de-referencing operator * (*rp).display(); Using the member access operator -> rp -> Display(); 69

Dynamic Allocation of a Class Object Consider the Rational class defined before Rational *rp; int a, b; cin >> a >> b; rp = new Rational(a,b); rp -> Display(); // (*rp).display(); delete rp; rp = NULL; 70

Next week: lists Questions? 71