Pointers. Variable Declarations Declarations served dual purpose –Specification of range of values and operations –Specification of Storage requirement.

Slides:



Advertisements
Similar presentations
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Advertisements

Names and Bindings.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Kernighan/Ritchie: Kelley/Pohl:
Informática II Prof. Dr. Gustavo Patiño MJ
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers. 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.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Names and Bindings Introduction Names Variables The concept of binding Chapter 5-a.
Chapter 12 Pointers and linked structures. 2 Introduction  The data structures that expand or contract as required during the program execution is called.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Multi-Dimensional Arrays
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Names Variables Type Checking Strong Typing Type Compatibility 1.
CSC Programming I Lecture 8 September 9, 2002.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Basic Semantics Associating meaning with language entities.
Module and Data Sharing. Programming in the Large Software, in general, is large having multiple units Multiple units designed and developed independently.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
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.
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.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
SE424 Languages with Context A Block Structured Language.
C Programming – Part 3 Arrays and Strings.  Collection of variables of the same type  Individual array elements are identified by an integer index 
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
1 CS Programming Languages Class 09 September 21, 2000.
ISBN Chapter 6 Data Types Pointer Types Reference Types Memory Management.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
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.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
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.
Data Types Chapter 6: Data Types Lectures # 13. Topics Chapter 6: Data Types 2 Introduction Primitive Data Types Character String Types Array Types Associative.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Object Lifetime and Pointers
Dynamic Storage Allocation
Data Types In Text: Chapter 6.
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Dynamic Memory Allocation
Complex Data Types One very important measure of the “goodness” of a PL is the capability of its data types to model the problem space variables Design.
Presentation transcript:

Pointers

Variable Declarations Declarations served dual purpose –Specification of range of values and operations –Specification of Storage requirement All programs required FIXED amount of memory –number of variables fixed by the declaration –decided by their types One exception: Allocatable array –Size of the array depends upon input

Static and Dynamic Allocation Compiler uses the declaration to allocate memory for a program Static allocation (or fixed memory requirements) leads you to be conservative Wastage of space and poor performance for some inputs Analogy: Two-way traffic in City roads Better management: allocate on demand –Initially allocate minimal –Allocate more when needed –Deallocate when not needed –Dynamic Memory management

Dynamic Memory allocation Memory allocation not fixed nor done at compile-time It is done at run-time at run-time no declarations - only executable instructions need special instructions for allocation - executable declarations so to say Allocate and Deallocate constructs for dynamic arrays we need more general mechanism for arbitrary organization of data

Pointers One problem with dynamic allocation: How do we access the newly allocated memory locations How did we access the statically allocated memory? Access the new locations by their addresses This is against the principle of high level languages: –abstract memory locations and machine details –disallow direct control over resources – unsafe is there any other way? pointer variables is a compromise Pointer variable contains addresses rather than data values Addresses point to the newly allocated memory locations and hence called pointers

Pointer variables They store addresses that identify locations where actual data values reside Pointer variables declared statically so compiler can allocate memory Static declaration of pointer variables! That is funny –we do not know a priori our memory requirement and hence our quest for dynamic memory locations Static declarations can allocate only a fixed number of pointers How do we create and access unbounded number of locations Answer: Dynamic creation of pointers themselves (more on this later)

Pointer variable Declarations Declarations specify types - set of data values and operations What types pointers are or should be? Pointer variables store addresses Addresses are numerical values - non negative integers Are they non negative integers? No, quite a different kind Pointers always contain same type of values whatever they point to –Can point to integers, reals, characters, arrays or structures Are all pointers of the same type

Pointers are of different types Only way of accessing dynamic objects is through pointers What is pointed to is distinguished - real, integer, character, array etc. Essential to distinguish the pointers for the same reason So Pointers are of different types: –integer pointer, real pointer, array pointer, etc Pointer types are decided by the types of those pointed to Declarations specify these

Pointer Declarations Examples: integer, pointer:: p1, p2 real, pointer:: r1, r2 integer, dimension(:), pointer:: array_ptr real, dimension(:,:), pointer:: matrix_ptr These declarations allocate memory for the pointer variables Pointer variables have addresses like normal addresses But they store addresses - the addresses will be assigned dynamically (during execution) Addresses assigned should correspond to locations where data values with the specified type is stored Special statements are provided for this purpose

Target variables Simplest pointer assignment: –store the address of a location allocated for a variable Example: p1 => x r1 => z matrix_ptr => m where –p1,r1, matrix_ptr as before –x,z,m are integer, real and matrix variables The types should match rhs variables resolved to addresses! –contrast with conventional assignment

Pointer assignment x z m p1 r1 matrix_ptr

Target declarations For a variable to act as target explicit declaration required: integer, target :: x real, target :: z integer, dimension(10,10), target :: matrix_ptr

Targets can be pointers Suppose p1 and p2 are of pointers of the same type Further suppose p2 points to a location of appropriate type Then p1 => p2 makes p1 point to whatever p2 points to

Before Assignment p1 p2

After assignment p1 p2

Dereferencing of pointers Two meanings for pointers in p1 => p2 p2 has an address and contains another address What is assigned to p1 is the content of p2 p2 on the rhs refers to the contents of p2 rather than p2 itself This is called Dereferencing Contrast this when target is ordinary variable p1 => x –what is assigned here is not the content of x but the address of x

Another example Consider write *, p1, p2 What is printed? The address associated with p1,p2? No, the values stored at those addresses The pointers are dereferenced to get the values

Pointers in Normal Assignment Pointers can appear in normal assignments: 1. p1 = p2 2. p1 = p2 + p3 Suppose, p1, p2 and p3 points to targets x, y and z The above is equivalent to 1. x = y 2. x = y + z Note that p1 is also dereferenced here

Rules for dereferencing => The lhs should be evaluated to an address (or pointer) The rhs should also evaluate to an address = The lhs should evaluate to an address The rhs should evaluate to a value print *, x –x should be a value So the rule is: Dereference the pointer as much required to evaluate to appropriate value

Use of Pointers Suppose you wish to exchange two arrays arr1, arr2 of Dimension(100,100) Solution 1: temp = arr1 arr1 = arr2 arr2 = temp involves exchange of 10,000 values! Solution 2: Real, Dimension(:,:), pointer:: p1,p2,temp p1 => arr1 p2 => arr2 temp => p1 p1 => p2 p2 => temp Exchange of just two pointers

Dynamic Allocation of Memory So far, pointers point to already existing variables The amount of used memory is still static For dynamic memory requirement, additional mechanism needed Allocate and Deallocate instructions Allocate ‘creates’ required memory and decllocate ‘destroys’ memory

Allocate Command Simplest allocate statement Allocate(p, stat = s) This allocates appropriate memory space, address pointed to by the pointer p s returns an integer value which indicates whether allocation successful or not s = 0 means success, failure otherwise Stat = is optional but should always be used If allocation fails and if no stat = clause, then the program will abort

Some examples integer, pointer:: p1 integer, dimension(:):: p2... allocate(p1, Stat=p1_stat) allocate(p2(1:10), Stat = p2_stat) '''" p1 = x + y p2(2) = p2(1) + p1 Note the dimension specification in p2 declaration

Deallocate Command Memory created using Allocate command can be destroyed when not needed –Deallocate(p, Stat = p_stat) Deallocates the memory, if p_stat = 0 What does p point to after this command? It points to null value Pointer assignment or allocation associates the pointer with some address Deallocation breaks this association Referring to pointer that is disassociated is an error –The program will abort

Checking Association To avoid aborting, association status of pointer should be checkable Intrinsic function Associated used for this purpose associated(p) returns the value.TRUE. iff p is associated with a target A more general form is associated(p, tvar) returns.TRUE iff p is associated with the target tvar Association with a pointer can be removed using nullify(p) which disassociates p with any target.

Pointers - serious safety hazard Conventional variables have many nice features: –unique association of memory with variables –distinct variables - distinct locations –one without the other not possible Pointers provides flexibility and more control But at the cost of safety It is a low-level feature No unique association of pointers to targets More than one pointer to the same target or location Pointer without location (dangling pointers)! Location without any pointers too (memory leak or garbage)!

Multiple Associations p1 => x p2 => p1 p3 => p2 p4 => x All point to the same location p1 p2 p3 p4 x

Dangling Pointers What is the problem with multiple associations? value pointed to by p1 can be changed independently p1 = 10 p2 = 17 p1 = p1 + 1 p1 points to a location which contains 18 and not 11 More serious problem: p1 = 10 deallocate(p2) p1 = p1 + 2 p1 is pointing to a location which is deallocated p1 is a dangling pointer no control over what value the deallocated memory will contain

Memory Leak Only way of accessing dynamically allocated memory is via pointers Suppose there is only one pointer p pointing a location nullify(p) disassociates p The memory is no longer accessible Memory has leaked out - memory has become garbage Deallocation done before memory leaks out Wastage of space Separate Garbage collection phase