© Janice Regan, CMPT 128, February. 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students Pointers.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Chapter 6 Data Types
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
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’;
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Memory Allocation Ming Li Department.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Pointers.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Stack and Heap Memory Stack resident variables include:
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
C++ Memory Overview 4 major memory segments Key differences from Java
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
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.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Slide 1 Chapter 10 Pointers and Dynamic Arrays. Slide 2 Learning Objectives  Pointers  Pointer variables  Memory management  Dynamic Arrays  Creating.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers and Dynamic Arrays
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students, continue; and break; statements.
Pointers and Arrays Dynamic Variables and Arrays.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Pointers CSC1201: Programming Language 2. Topics Pointers ▫Memory addresses ▫Declaration ▫Dereferencing a pointer ▫Pointers to pointer.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Pointers and Dynamic Arrays
Pointers and Dynamic Arrays
Day 03 Introduction to C.
Introduction to Programming
Pointers, Polymorphism, and Memory Allocation
Programmazione I a.a. 2017/2018.
Day 03 Introduction to C.
COMP 2710 Software Construction Pointers
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Presentation transcript:

© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers

© Janice Regan, CMPT 128, Dynamic and Automatic Variables  Dynamic variables  Created during program execution  Destroyed during program execution  Must remember to destroy all dynamic variable created  Automatic variables  Declared within function definition  Not dynamic Automatically created when function is called Automatically destroyed when function call completes  Function scope local variables are an example

Dynamic variables: creation  C++  Use the keyword new int *myVariablePointer; myVariablePointer = new int;  Variable can only be referenced using the pointer myVariablePointer  Variable does not have an identifier (name) © Janice Regan, CMPT 128,

Dynamic variables: creation  C  Use function malloc() int *myVariablePointer; myVariablePointer = (int *)malloc( sizeof(int) );  Variable can only be referenced using the pointer myVariablePointer  Variable does not have an identifier (name) © Janice Regan, CMPT 128,

Dynamic variables: destruction  If you dynamically allocate a variable you must also destroy it after you are finished it.  C use free  C++ use delete © Janice Regan, CMPT 128,

Dynamic variables: creation  C++  Use the keyword delete int *myVariablePointer; myVariablePointer = new int; … delete myVariablePointer; © Janice Regan, CMPT 128,

Dynamic variables: destruction  C  Use function free() int *myVariablePointer; myVariablePointer = (int *)malloc( sizeof(int) ); ……. free (myVariablePointer) © Janice Regan, CMPT 128,

7 Initializing pointers  After you declare a pointer double *v1p, v1, *v2p, *v3p;  It is good programming practice to initialize the pointer to NULL or some other particular value. v1p = (double *)malloc( sizeof(double) ); v2p = NULL; v3p = new int;  Now consider the new (C++) and malloc() (C)

© Janice Regan, CMPT 128, Automatic variables  When you declare an automatic variable  you provide an identifier  memory is allocated for the variable at compile time (within the executable)  The allocated memory is available till the program terminates  The variable is referred to by the provided identifier

© Janice Regan, CMPT 128, Memory Management  Heap memory or freestore memory  Reserved for dynamically-allocated variables  All new dynamic variables consume heap memory  Possible to consume all heap memory If all heap memory is consumed further allocations of dynamic variables will fail interaction with your computer’s virtual memory system may cause unexpected behavior Your program may not know when heap is exhausted

© Janice Regan, CMPT 128, Dynamic variables  When you create a dynamic variable  you provide a pointer to a variable of the type of the variable you wish to create  memory is allocated for the pointer to the variable at compile time  You use new or malloc() to create the variable while your program is running (from heap storage)  You are responsible for freeing or deleting the memory before your program terminates

© Janice Regan, CMPT 128, C++ Using the new Operator  Operator new dynamically creates variables of any type, for example double *v3p; v3p = new double;  creates a new double variable  Value of expression ( new double ) is a pointer to the new double variable.  The new variable has no identifier  The pointer to the new variable is assigned to (placed in) pointer to a double variable v3p.

© Janice Regan, CMPT 128, Pointers in assignment statements  double *v3p;  v3p = new double; ? v3p Pointer Identifier Value of pointer variable 1004 v3p address Pointer Identifier Value of pointer variable ? Variable Identifier Variable Value

© Janice Regan, CMPT 128, Pointers in assignment statements  double *v3p;  v3p = new double(77.2); ? v3p Pointer Identifier Value of pointer variable 1004 v3p address Pointer Identifier Value of pointer variable 77.2 Variable Identifier Variable Value

© Janice Regan, CMPT 128, new Success – New Compiler  Compilers following standards after 2002:  If new operation fails: Program terminates automatically Produces error message  Can still make your program continue after a failed allocation by  Catching the exception (more later)  Using a modified version of the NULL check

© Janice Regan, CMPT 128, Checking new Success  Can still test if null returned by call to new: int *p; p = new(nothrow) int; if (p == NULL) { cout << "Error: Insufficient memory.\n"; // exit if this is a critical allocation // otherwise continue }

© Janice Regan, CMPT 128, Other examples of ‘new’ int *ap=NULL; double *bp=NULL; double *dp = NULL; char *cp = NULL; ap = new int; bp = new double; cp= new char[23]; dp = new double[100];

© Janice Regan, CMPT 128, C Using malloc()  Operator new dynamically creates variables of any type, for example int *v3p; v3p = (int*)malloc(sizeof(int));  creates a new integer variable  Function malloc returns a void pointer to the new variable. You cast the pointer  The new variable has no identifier  The pointer to the new variable is assigned to (placed in) pointer to integer variable v3p.

© Janice Regan, CMPT 128, Pointers in assignment statements  int *v3p;  v3p = (int*)malloc(sizeof(int)); ? v3p Pointer Identifier Value of pointer variable 1004 v3p address Pointer Identifier Value of pointer variable ? Variable Identifier Variable Value

© Janice Regan, CMPT 128, Checking malloc() Success  Test if null returned by call to malloc(): int *p = NULL; p = (int*)malloc(sizeof(int)); if (p == NULL) { cout << "Error: Insufficient memory.\n"; // exit if this is a critical allocation // otherwise continue }

© Janice Regan, CMPT 128, Other examples of malloc() int *ap=NULL; double *bp=NULL; double *dp = NULL; char *cp = NULL; ap = (int *)malloc( sizeof(int)); bp = (double *)malloc(sizeof(double)); cp = (char *)malloc( 23*sizeof(char)); dp = (double *) malloc( 100*sizeof(double));

© Janice Regan, CMPT 128, Memory management  We have seen half of the tools needed for memory management in C++  We can create variables dynamically  The other half is to be able to destroy the dynamic variables we have created after we are done with them.  Destroying variables we have created is our responsibility, must assure that all dynamically allocated variables are destroyed so that the memory allocated to them can be returned to the heap  To destroy dynamically allocated variables use the delete operator

© Janice Regan, CMPT 128, C++ delete Operator  De-allocate dynamic memory  Returns memory to the heap  Example: int *v1p; p = new int(5); … //Some processing… delete p;

© Janice Regan, CMPT 128,  De-allocate dynamic memory  Returns memory to the heap  Example: int *p; p = (int *)malloc( sizeof(int) ); *p = 5; … //Some processing… free(p); C free() Function

© Janice Regan, CMPT 128, C++ creating and deleting arrays  Creates an array of integers of size 5  After using the array deletes the memory that was used for the array int *p; p = new int[5]; … //Some processing… delete [ ] p;

© Janice Regan, CMPT 128,  Creates an array of integers of size 5  After using the array frees the memory that was used for the array int *p; p = (int *)malloc( 5* sizeof(int) ); … //Some processing… free(p); C creating and deleting arrays

© Janice Regan, CMPT 128, Potential problems  It is possible to  Try to access memory you have already deleted:  Lose all references to a piece of memory and be prevented from deleting that memory Means the heap is reduced in size for the rest or your program and for other programs run after your program completes. Memory that is dynamically allocated but not deleted may not be returned to heap

© Janice Regan, CMPT 128, Memory Leaks  Beware; do not loose your last reference to memory thatwas allocated using new or malloc() v1p v2p v1p v2p All reference to this memory has been lost. It is assigned to the program but cannot be used or deleted. It has 'leaked' from memory management within the program. Available heap has been decreased. v2p = new int; v2p = (int *)malloc(sizeof(int));

© Janice Regan, CMPT 128, C++ Dangling Pointers  delete p; // terminate allocation of memory // pointed to by p  The program no longer owns the memory pointed to by p but p still points to that memory p is now a dangling pointer If p is dereferenced ( *p ) results are not predictable  Avoid dangling pointers  Assign pointer to NULL after delete: delete p; // p still points to the previously allocated memory p = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.

© Janice Regan, CMPT 128, C Dangling Pointers  free(p); // terminate allocation of memory // pointed to by p  The program no longer owns the memory pointed to by p but p still points to that memory p is now a dangling pointer If p is dereferenced ( *p ) results are not predictable  Avoid dangling pointers  Assign pointer to NULL after delete: free(p); // p still points to the previously allocated memory p = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.

© Janice Regan, CMPT 128, C Dangling Pointers  free(p); // terminate allocation of memory // pointed to by p  The program no longer owns the memory pointed to by p but p still points to that memory p is now a dangling pointer If p is dereferenced ( *p ) results are not predictable  Avoid dangling pointers  Assign pointer to NULL after delete: free(p); // p still points to the previously allocated memory p = NULL; // p now points “nowhere” attempts at // dereferencing will cause a predictable error.