Dynamically Allocated Memory

Slides:



Advertisements
Similar presentations
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Advertisements

Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
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.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Run-Time Storage Organization
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.
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.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
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.
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. This is.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More C++ Features True object initialisation
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Memory Management in Java Mr. Gerb Computer Science 4.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers and Dynamic Memory Allocation
Yan Shi CS/SE2630 Lecture Notes
Memory Management.
Yan Shi CS/SE 2630 Lecture Notes
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Data Types In Text: Chapter 6.
Learning Objectives Pointers as dada members
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Programming with ANSI C ++
Class: Special Topics Copy Constructors Static members Friends this
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
This pointer, Dynamic memory allocation, Constructors and Destructor
Dynamic Memory Review what is static, automatic, dynamic variables? why are dynamic(ally allocated) variables needed what is program stack? function.
Pointers and Dynamic Variables
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Classes with Dynamically Allocated Data
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Chapter 15 Pointers, Dynamic Data, and Reference Types
Indirection.
Chapter 15-3 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Dynamic Memory.
Class: Special Topics 2 For classes using memory allocation
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Copy Constructors and Overloaded Assignment
Run-time environments
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Dynamically Allocated Memory pointer variables and the heap

Pointer Variables a pointer is a variable which holds the address of something else called indirect addressing . pointer what is pointed to a value of some type

“Do not mistake the pointing finger for the moon” a Zen saying

Some Uses of Pointer Variables reference parameters in C++ and class instances in Java the pointer is "hidden" dynamically (run-time) allocated arrays linked data structures linked lists

"lifetime" of a variable is a run-time concept period of time during which a variable has memory space associated with it begins when space is allocated ends when space is de-allocated three categories of "lifetime" static - start to end of program execution automatic (stack) - start to end of declaring function's execution heap - starts with "new"; ends when: Java: run-time system collects "garbage" C++: "delete" statement executed

data memory model space for global variables static data run-time stack - activation records added and removed as program runs (expands and shrinks in an orderly LIFO manner) automatic data space for variables allocated at run-time using "new" (allocation and de-allocation requests occur in unpredictable order) heap data

Heap Variables are accessed indirectly via a pointer variable memory space is explicitly allocated at run-time (using new) space is allocated from an area of run-time memory known as the heap in C++ space must be explicitly returned (using delete) to avoid “memory leak” C++ programmers are responsible for memory management

Declaring Pointer Variables syntax <data type> * <pointer name>; pointers are typed some examples int * intPointer; Time * timePointer; intPointer and timePointer are automatic variables ? intPointer timePointer ?

Assigning a value to a pointer variable the value of a pointer variable is a memory address assign address of an existing variable int number; intPointer = &number; use "new" to allocate space in the heap intPointer = new int; address of heap memory space allocated becomes the value of the pointer variable ? intPointer heap memory

Dereferencing heap variables do not have a name of their own are anonymous variables *intPointer refers to the value pointed to by intPointer intPointer is the finger; *intPointer is the moon what happens? intPointer = 36; *intPointer = 36; (*intPointer)++; cout << *intPointer; intPointer = null; intPointer *intPointer

Returning Heap Space done by using the delete statement syntax example delete <pointer variable>; example float * fPointer = new float; cin >> (*fPointer); ------ delete fPointer;

Pointers - Summary a pointer variable holds a memory address and can be used to create and access dynamic variables dynamic (heap) variables are explicitly created at run-time (using new) memory for dynamic variables is allocated in an area of memory called the heap space used for dynamic variables needs to be freed (using delete) to avoid memory leaks

using pointers to dynamically allocate arrays Using C++ for an example

a C++ automatic array int entry [31]; entry 34 45 15 ---------- 36 value has to be known at compile time entry 34 45 15 ---------- 36 0 1 2 ----------- 30 NO HEAP MEMORY SPACE IN USE! entry[0] = = *entry

C++ dynamic arrays can use dynamic memory allocation to postpone decision about array capacity until run-time array space will be on the heap pointer to array's beginning is not on the heap float * dynArray; // declare pointer only dynArray = new float [max]; // max is a variable // use of dynamic array the same as use of an automatic array delete [ ] dynArray; // free heap space

Stack class using a dynamic array changes needed ? data structure has changed so private data members will be different constructor has to allocate the dynamic array needs parameter to indicate capacity once allocated capacity does not change operations are the same data member rather than constant for capacity use of the heap requires added methods destructor, copy constructor, operator=

Stack class data members needed? Constructor SE * myArray; int myTop; int myCapacity; Constructor must allocate the dynamic array needs a parameter to know how big an array to allocate myArray myTop myCapacity someStack Stack::Stack (int size) { myCapacity = size; myArray = new SE[myCapacity]; assert (myArray != null); myTop = -1; }

a Stack object void func ( ) { Stack someStack (5); ------ } myArray myTop myCapacity someStack -1 5 This space in on the heap when func returns space for its activation record on the run-time stack is reclaimed This space in on the stack

destructor needed in order to prevent "memory leaks" heap memory space which is no longer accessible but has not been returned (using delete) destructor is a method that is called implicitly when the function in which an object was declared returns compiler provides a "default destructor" nothing more is needed unless the object makes use of heap memory space (allocates space using new) to provide a destructor for Stack in declaration: ~Stack( ); // class destructor in implementation: Stack::~Stack( ) { delete [ ] myArray; }

copy constructor needed in order to make a deep rather than a shallow copy of an object when is a copy of an object made? a value parameter requires a copy of the argument void someFunc (Stack s) { ---- } one object is created as a copy of an existing object Stack a (10); Stack b = a; // or Stack b (a); a function/method returns an object Stack func ( ) { Stack stackToBeReturned (8); ----- return stackToBeReturned; }

a shallow copy compiler provides a default copy constructor it makes a shallow copy when a copy is needed nothing more is needed unless the object makes use of heap memory space (allocates space using new) myArray myTop myCapacity b 5 8 Stack a (8); Stack b (a); 5 8 myArray myTop myCapacity a

a deep copy the copy must have its own heap memory space, the contents of which is the same as the object it is a copy of myArray myTop myCapacity b 5 8 Stack a (8); Stack b (a); 5 8 myArray myTop myCapacity a

a copy constructor myClass (const myClass & sourceObj); myClass::myClass (const myClass & sourceObj) { //copy all non-heap data members using = //allocate heap space required by the copy //copy data stored in sourceObj's heap //memory to new object's heap memory } makes a new deep copy of an existing object

copy constructor for Stack class declaration Stack (const Stack & sourceStack); Stack::Stack (const Stack & sourceStack) { myCapacity = sourceStack.myCapacity; myTop = sourceStack.myTop; myArray = new SE [myCapacity]; assert (myArray != null); for (int pos = 0; pos < myTop; pos++) { myArray[pos] = sourceStack.myArray[pos]; } implementation

= replaces an object with a copy of an existing object stackA = stackB; compiler provided operator= replaces stackA with a shallow copy of stackB heap space used by the "old" stack A becomes garbage a class using heap memory must provide its own operator= return heap memory currently used by stackA replace stackA with a deep copy of stackB

same job that is done by the copy constructor operator= void operator= (const myClass & SourceObj); void myClass::operator= (const myClass & SourceObj); { //deallocate heap space used by left hand operand //copy all non-heap data members using = //allocate new heap space for the left hand operand //copy data stored in sourceObj's heap memory //to left hand operand's heap memory } same job that is done by the copy constructor

operator= for Stack class declaration void operator= (const Stack & sourceStack); void Stack::operator= (const Stack & sourceStack) { if (this != &sourceStack) // check for self copy delete [ ] myArray; // deallocate previous array // same code as in the copy constructor // to make a deep copy of sourceStack } implementation