James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.

Slides:



Advertisements
Similar presentations
James Tam Linked Lists in Pascal Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
Advertisements

Programming Languages and Paradigms
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
CSI 3120, Implementing subprograms, page 1 Implementing subprograms The environment in block-structured languages The structure of the activation stack.
1 Compiler Construction Intermediate Code Generation.
Chapter 7: User-Defined Functions II
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
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.
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
James Tam Intermediate Pascal to Java examples Pascal To Java: The Transition Documentation Variables and constants Advanced input and output Decision.
James Tam Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
J. Michael Moore Arrays CSCE 110 From James Tam’s material.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
Run-Time Storage Organization
Topic 8 – Introduction to Pointers and Function Output Parameters.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
J. Michael Moore Arrays CSCE 110. J. Michael Moore Typical (although simplified) Problem Write a program that will track student grades in a class. The.
James Tam Pointers In this section of notes you will learn about a third type of variable that stores addresses rather than data.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.
Pointers Applications
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
J. Michael Moore Modules – the Basics CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
1 Contents. 2 Run-Time Storage Organization 3 Static Allocation In many early languages, notably assembly and FORTRAN, all storage allocation is static.
Review of C++ Programming Part II Sheng-Fang Huang.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
Runtime Environments Compiler Construction Chapter 7.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Pointers OVERVIEW.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
Programming Languages and Paradigms Imperative Programming.
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.
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.
Object-Oriented Programming in C++
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.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
ISBN Chapter 10 Implementing Subprograms.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
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.
Dynamic Storage Allocation
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Pointers, Dynamic Data, and Reference Types
Objectives You should be able to describe: Addresses and Pointers
Arrays In this section of notes you will be introduced to a homogeneous composite type, one-dimensional arrays One-dimensional arrays in Pascal.
Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays Homogeneous.
Dynamic Memory.
Course Overview PART I: overview material PART II: inside a compiler
Presentation transcript:

James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data

James Tam Memory: What You Know Memory is analogous to a series of slots each of which can store a single piece of information S.F. Adams 1001 S. Bill 1002 C. Brown 1003 J. Chan ‘j’ 4.0

James Tam Memory: What You Will Learn How a memory location can contain the address of another location in memory S.F. Adams 1001 S. Bill 1002 C. Brown 1003 J. Chan

James Tam Why Bother With Pointers? The answer to this question will be deferred until the next section of notes (linked lists).

James Tam Types Of Variables: What You Know Pascal Variables a. Simple (atomic) b. Aggregate (composite) integercharbooleanreal Homogenous (arrays) Heterogeneous (records) 1.Data

James Tam Types Of Variables: What You Will Learn Pascal Variables a. Simple (atomic) b. Aggregate (composite) integercharbooleanreal Homogenous (arrays) Heterogeneous (records) 1.Data 2. Addresses (pointers)

James Tam Declaration Of Pointer Variables Format: type type name = ^ type pointed to 1 ; : : begin var pointer name : type name; Example: type IntegerPointer = ^integer; : : begin var numPtr1 : IntegerPointer; 1 An alternative is to use the instead of the “up-arrow” ^ to declare a pointer variable (not recommended)

James Tam Allocating Memory For Pointers It involves reserving some dynamic memory and having the pointer point to that memory. Format new (pointer name); Example new (numPtr1);

James Tam De-Allocating Memory For Pointers Returning back the dynamically allocated memory (if it’s needed it can then be re-used for something else). Format dispose (pointer name); Example dispose (numPtr1);

James Tam De-Allocating Memory For Pointers: Followup Should also be followed by having the pointer no longer point to the memory that has just been de-allocated Format: pointer name := NIL; Example: numPtr1 := NIL;

James Tam Using Pointers Important! Are you dealing with the pointer or what the pointer is pointing to (allocated memory)? Pointer name Pointer name ^ (de-reference pointer)

James Tam Using Pointers Important! Are you dealing with the pointer or what the pointer is pointing to (allocated memory)? Pointer name Pointer name ^ (de-reference pointer) pointer X variable

James Tam Accessing Pointers Format: (Pointer) pointer name (Memory pointed to) pointer name ^

James Tam Accessing Pointers (2) Example: type IntegerPointer = ^integer; : : begin var numPtr1 : IntegerPointer; new(numPtr1); (Pointer) writeln(numPtr1); (Memory pointed to) writeln(numPtr1^);

James Tam Accessing Pointers (2) Example: type IntegerPointer = ^integer; : : begin var numPtr1 : IntegerPointer; new(numPtr1); (Pointer) writeln(numPtr1); (Memory pointed to) writeln(numPtr1^);

James Tam Accessing Memory Allocated Through A Pointer Normally memory is accessed through a variable name: var num : integer; num := 12; A pointer is a variable and the pointer can be accessed through the name of the pointer: type IntegerPointer = ^integer; begin var numPtr : IntegerPointer; new(numPtr); However the memory allocated through the pointer (referred to by the pointer) can only be accessed through the pointer

James Tam Accessing Memory Allocated Through A Pointer (2) In a similar fashion if you have the address of a location in memory then it may be accessed or modified without using a variable name. This is precisely how variable parameters (pass by reference) are implemented!

James Tam Using Pointers : Allowable Operations Assignment := Relational Equality = Inequality <> For the following slides assume that the following statements: var numPtr1 : ^integer; var numPtr2 : ^integer; new(numPtr1); numPtr1^ := 1; new(numPtr2); numPtr1^ := 2;

James Tam Using Pointers : Assignment Format: (Pointer) pointer name := pointer name; (Memory pointed to) pointer name ^ := expression; Example: (Pointer) numPtr1 := numPtr2; (Memory pointed to) numPtr1^ := 100;

James Tam Using Pointers : Allowable Operations (Equality) Format: (Pointer) if (pointer name 1 = pointer name 2) then (Memory pointed to) if (pointer name 1^ = pointer name 2^) then Example: (Pointer) if (numPtr1 = numPtr2) then (Memory pointed to) if (numPtr1^ = numPtr2^) then

James Tam Using Pointers : Allowable Operations (Inequality) Format: (Pointer) if (pointer name 1 <> pointer name 2) then (Memory pointed to) if (pointer name 1^ <> pointer name 2^) then Example: (Pointer) if (numPtr1 <> numPtr2) then (Memory pointed to) if (numPtr1^ <> numPtr2^) then

James Tam Pointers : First Example program pointer1 (output); type IntegerPointer = ^integer; begin var num: integer; var numPtr1: IntegerPointer; var numPtr2: IntegerPointer; writeln('Example 1'); num := 10; new(numPtr1); new(numPtr2); numPtr1^ := 100; numPtr2^ := 100; writeln('num = ':11, num:3); writeln('numPtr1^ = ':11, numPtr1^:3); writeln('numPtr2^ = ':11, numPtr2^:3);

James Tam Pointers : First Example (2) if (numPtr1 = numPtr2) then writeln('Same memory') else writeln('Separate memory'); if (numPtr1 ^= numPtr2^) then writeln('Same data') else writeln('Different data'); (* Not allowed *) (*writeln('numPtr1=',numPtr1); *) writeln('Example 2'); num := numPtr1^; writeln('num = ':11, num:3); writeln('numPtr1^ = ':11, numPtr1^:3); num := 33; writeln('num = ':11, num:3); writeln('numPtr1^ = ':11, numPtr1^:3); writeln;

James Tam Pointers: First Example (3) writeln('Example 3'); numPtr2 ^ := 66; numPtr1 := numPtr2; if (numPtr1 = numPtr2) then writeln('Same memory') else writeln('Separate memory'); numPtr2^ := 33; writeln('numPtr1^ = ':11, numPtr1^); writeln('numPtr2^ = ':11, numPtr2^); dispose(numPtr1); (* dispose(numPtr2); *) (* Indicating that neither pointer points to any memory *) numPtr1 := NIL; numPtr2 := NIL; end.

James Tam RAM: How Things Are Divided Up Executable e.g., a.out (binary, machine language instructions) Static memory: global constants and variables Dynamic memory: ‘The stack’ for parameters and local variables Dynamic memory: ‘The heap’ for memory allocated through a pointer Memory that’s allocated for programs that are running THE HEAP new (pointer); THE STACK procedure proc (num1 : integer); var num2 : integer; begin var num3 : integer; end; GLOBALS program test; const SIZE= 10; var num : integer; begin end.

James Tam Pointers And Parameter Passing Value parameters In the call to the module what’s passed in is a copy of the value stored in the parameter. The header for the module declares the name of the local identifier/local variable used to store the value stored in the parameter. Variable parameters In the call to the module what’s passed in is the address of the variable. The header for the module declares the name of the local pointer that is used to store the address of the parameter. The pointer is automatically de-referenced (to change the original parameter) whenever the local identifier is accessed.

James Tam Pointers And Parameter Passing (2) program parameters (output); procedure proc ( num1 : integer; var num2 : integer); begin num1 := 10; num2 := 20; end; begin var num1 : integer; var num2 : integer; num1 := 1; num2 := 2; proc(num1,num2); end.

James Tam Parameter Passing: Rules Of Thumb You Should Know For Data Parameters Value parameters Data: What’s passed in cannot change (changes are made to a local copy). Variable parameters Data: What’s passed in can change (changes are made to the original parameter)

James Tam Parameter Passing: Rules Of Thumb You Should Learn For Pointer Parameters Value parameters (pointer parameter) Pointers: What’s passed in (a pointer) cannot change (changes are made to a local copy of the pointer). Variable parameters (pointer parameter) Pointers: What’s passed in (a pointer) can change (changes are made to the original pointer parameter) Value or variable parameters (what the pointer parameter points to) Value parameter: —A local copy of the pointer is made for the module which contains the address of a data variable. —This allows the data referred to by the pointer to be changed. Variable parameter: —The address of the pointer parameter is passed to another local pointer (pointer to a pointer). —Again this allows the data referred to by the pointer to be changed.

James Tam Pointers As Value Parameters Need to define a type for the pointer first! Format (defining a type for the pointer): type = ^ ; Format (passing pointer): procedure procedure name (pointer name (1) : type of pointer (1); pointer name (2) : type of pointer (2); : : pointer name (n) : type of pointer (n)); function function name (pointer name (1) : type of pointer (1); pointer name (2) : type of pointer (2); : : pointer name (n) : type of pointer (n));

James Tam Pointers As Value Parameters (2) Example (defining a type for the pointer) type CharPointer = ^char; Example (passing pointer): procedure proc1 (aCharPointer : CharPointer ); begin: end;

James Tam Pointers As Variable Parameters Need to define a type for the pointer first! Format (defining a type for the pointer): type = ^ ; Format (passing pointer): procedure procedure name (var pointer name (1) : type of pointer (1); var pointer name (2) : type of pointer (2); : : var pointer name (n) : type of pointer (n)); function function name (var pointer name (1) : type of pointer (1); var pointer name (2) : type of pointer (2); : : var pointer name (n) : type of pointer (n));

James Tam Pointers As Variable Parameters Need to define a type for the pointer first! Example (defining a type for the pointer) type CharPointer = ^char; Example (passing pointer): procedure proc1 (var aCharPointer : CharPointer ); begin: end;

James Tam Pointers: Second Example A full version of this program can be found in Unix under: /home/231/examples/pointers/pointer2.p program pointer2 (output); type CharPointer = ^char; procedure proc1 (charPtr : CharPointer); var temp : CharPointer; begin writeln; writeln(‘Proc1'); new(temp); temp^ := 'A'; charPtr := temp; writeln('temp^ = ', temp^); writeln('charPtr^ = ', charPtr^); end;

James Tam Pointers: Second Example (2) procedure proc2 (var charPtr : CharPointer); var temp : CharPointer; begin writeln; writeln(‘Proc2'); new(temp); temp^ := 'A'; charPtr := temp; writeln('temp^ = ', temp^); writeln('charPtr^ = ', charPtr^); end;

James Tam Pointers: Second Example (4) begin(* Main program *) var charPtr : CharPointer; new (charPtr); charPtr^ := 'a'; writeln; writeln(‘Main program.'); writeln('charPtr^ = ', charPtr^); proc1(charPtr); writeln('After proc1'); writeln('charPtr^ = ', charPtr^); proc2(charPtr); writeln('After proc2'); writeln('charPtr^ = ', charPtr^); writeln; end.(* End of main program *)

James Tam Summary: Passing Pointers As Parameters Reminder of the notation Name of the XX Contents of the XXX The address of the variable The address that the pointer ‘points to’

James Tam Summary: Passing Pointers As Value Parameters Module1 calls Module2 and passes ‘aPointer’ as a value parameter e.g., ‘proc1’in the previous example module1 = ‘The Heap’ aPointer DATA Module2 (In: copy of aPointer) = Changes made in module2 via aPointer can change the data Changes made to aPointer in module2 only change the local pointer

James Tam Summary: Passing Pointers As Variable Parameters Module1 calls Module2 and passes ‘aPointer’ as a variable parameter e.g., ‘proc2’ in the previous example module1 = ‘The Heap’ aPointer DATA Module2 (In: pointer to pointer) = 100 Changes made in module2 via aPointer can change the data Changes made to aPointer in module2 can change aPointer in module1.

James Tam What You Know: How Segmentation Faults Are Caused By Indexing Beyond The Array Bounds RAM a.out [1] [2] [3] [4] list OK ??? CORE

James Tam What You Will Learn: How Segmentation Faults (Possibly Bus Errors) Can Be Caused By Incorrect Pointer Dereferencing A full version of this program can be found in Unix under: /home/231/examples/pointers/pointer3.p program pointer3 (output); type IntegerPointer = ^ integer; begin var numPtr1 : IntegerPointer; writeln('1'); numPtr1^ := 100; writeln('2'); numPtr1 := NIL; writeln('3'); numPtr1^ := 100; end.

James Tam Segmentation Fault A ‘memory access violation’ (an attempt is made to access a part of memory that is ‘forbidden’ to a program). Can be caused be programs that index beyond the bounds of an array. Can also be caused by programs that improperly de- referenced pointers. Bad!  Operating system Your program Not allowed

James Tam Bus Error Caused by a ‘faulty memory access’. May occur when a program tries to access a non-existent memory address. Could also be triggered by accessing beyond the bounds of an array or improperly de-referenced pointers. Bad!!!  Operating system Your program No where???

James Tam You Should Now Know How to declare new types that are pointers to data How to declare variables that are pointers The difference between static and dynamically allocated memory How to dynamically allocate memory How to de-allocate memory Why and when to set pointers to NIL How to access a pointer and how to access what the pointer points to How to assign values to a pointer and how to assign values to what the pointer points to What operations can be performed on pointers and how does each one work How to pass pointers as value and variable parameters How incorrect pointer usage results in problems with memory accesses such as segmentation faults and bus errors