Memory Management CS101 2012.1. Chakrabarti Variable storage thus far  Never used global variables  All variables allocated inside functions, passed.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

Lecture 6 Sept 11, 2008 Goals for the day: Linked list and project # 1 list class in STL (section 3.3) stack – implementation and applications.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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 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.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CS 2133: Data Structures Binary Search Trees.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers OVERVIEW.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
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 1 List Data Structure List operations List Implementation Array Linked List.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
CHAPTER 17 LINKED LISTS. In this chapter, you will:  Learn about linked lists  Become aware of the basic properties of linked lists  Explore the insertion.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
Object Oriented Programming COP3330 / CGS5409.  Aggregation / Composition  Dynamic Memory Allocation.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Linked Lists Assignment What about assignment? –Suppose you have linked lists: List lst1, lst2; lst1.push_front( 35 ); lst1.push_front( 18 ); lst2.push_front(
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Pointers and Dynamic Arrays
Data Structure Interview Question and Answers
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Dynamically Allocated Memory
Chapter 15 Pointers, Dynamic Data, and Reference Types
Programming Abstractions
Pointers & Dynamic Data Structures
Dynamic Memory.
COP 3330 Object-oriented Programming in C++
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Presentation transcript:

Memory Management CS

Chakrabarti Variable storage thus far  Never used global variables  All variables allocated inside functions, passed by value or reference to other functions  In case of non-collection variables, the storage was always taken from the stack  In case of collection variables, storage was taken from the stack and the heap, but we did not need to understand how, or interfere

Chakrabarti Want a variable to outlive its scope  Same customer can have a checking account and a fixed deposit  Should not make copies of customer record  Supposing address or phone changes Customer makeCustomer(…) { … } Vs. Customer *makeCustomer(…) { … }  For simplicity let’s start with int variables

Chakrabarti new and delete int *pi = new int; *pi = 5; cout << pi << ' ' << *pi + 1 << endl; delete pi; pi points to an integer Allocates four bytes fom heap The value is always accessed as *pi Returns four allocated bytes to system: do this exactly once! The value is always accessed as *pi

Chakrabarti Pointer syntax TypeName *pointerVariableName;  TypeName is int, float, double etc. or the name of a class like vector etc.  * is the “pointer access” or “pointer dereference” operator  To read or write the storage holding the value of type TypeName, use *pointerVariableName in either the lhs or rhs  To read or write the pointer itself use pointerVariableName without a star

Chakrabarti Allocating arrays in the heap int nn = 5; int *pi = new int[nn]; for (int ix=0; ix < nn; ++ix) { cout << pi[ix] << endl; cout << *(pi+ix) << endl; } delete [] pi; Type remains same Allocates in heap space for nn ints Returns space back to heap (which remembers size but won’t tell you) Looks like array access Contents of cell ix integers after address pi

Chakrabarti The null pointer  Address 0 is not a legal address to read/write  Programs reliably fail if they attempt to do so  Therefore, int *pa = 0; is a safe initializer until memory is allocated (or after it is freed)  But 0 is of type int, while pa is of type int * (pointer to int )  Therefore a type cast is required int *pa = (int*) 0;  Can do this will any type in place of int

Chakrabarti Null pointer for classes class Customer { public: static Customer * const null; }; Customer * const Customer::null = (Customer*) 0;  Can now use Customer::null anywhere  Cleaner than (Customer*) 0 everywhere

Chakrabarti Our own vector class: specification class Vector { public: Vector(); Vector(const Vector& other); ~Vector(); void insert(int p, float v); float remove(int p); float get(int p) const; int size() const; } Promises that these methods will not modify the Vector in any way Default constructor: empty vector Copy constructor Destructor

Chakrabarti Vector implementation  Three private fields  Native array pa of floats allocated on heap  int cap recording the number of floats that can fit in the array (capacity)  int siz recording the number of floats currently in the array (from position 0 onward)  Invariant: siz  cap  Run out of space: allocate larger array, copy  siz << cap : allocate smaller array, copy

Chakrabarti insert void insert(int p, float v) { if (siz + 1 <= cap) { // enough space } else { float *nPa = new float[siz+1]; int wx = 0, rx = 0; while (rx < p) { nPa[wx++] = pa[rx++]; } nPa[wx++] = v; while (rx < siz) { nPa[wx++] = pa[rx++]; } if (cap > 0) { delete [] pa; } cap = siz = siz + 1; pa = nPa; } pa p nPa v

Chakrabarti Our own queue class: specification class Queue { // of ints, say public: bool isEmpty() const; int removeFirst(); void pushLast(int val); void print() const; private: QueueElement *first, *last; };

Chakrabarti Queue implementation struct QueueElement { int value; QueueElement *next; QueueElement(int v) : value(v), next(null) { } }

Chakrabarti Printing a queue QueueElement *pqe = first; while (pqe != null) { cout value << endl; pqe = pqe->next; } valuenextvaluenext pqe

Chakrabarti Constructor and destructor Queue::Queue() { first=last=null; } Queue::~Queue() { while (first != null) { QueueElement *pQe = first; first = first->next; delete pQe; } first next pQe

Chakrabarti pushLast void Queue::pushLast(int val) { QueueElement *pQe = new QueueElement(val); if (first == null) { first = pQe; } if (last != null){ last->next=pQe; } last = pQe; } last val pQe

Chakrabarti removeFirst int Queue::removeFirst() { int ans = first->value; QueueElement *pQe = first; first = first->next; delete pQe; return ans; }

Chakrabarti Binary search tree  A binary tree is either empty  Or it has a root node  With two children left and right  Each of which is a binary tree  Suppose each node contains an int key  Assume no duplicate keys for starters  The tree is a search tree if All keys in left are smaller than the root All keys in right are larger than the root

Chakrabarti Search tree from main() TreeNode *root = null; for (;;) { int key; cin >> key; if (root == TreeNode::null) { root = new TreeNode(key); } else { root->insert(key); }

Chakrabarti Definition of the tree node struct TreeNode { const int key; TreeNode *left, *right; TreeNode(int _key) : key(_key) { left = right = null; } void insert(int nKey) { // while satisfying property } };

Chakrabarti insert, first cut if (nKey < key) { if (left == null) { left = new TreeNode(nKey); } else { left->insert(nKey); } else { // repeat above, right instead of left } Tedious, can be avoided if you have a good understanding of * and &

Chakrabarti void insert(int nKey) TreeNode*& child = nKey < key? left : right; if (child == null) { child = new TreeNode(nKey); } else { child->insert(nKey); } child is a reference to a pointer to a TreeNode Recursive call from child node

Chakrabarti How to print the keys in order void print() { if (left != null) left->print(); cout << key << ' '; if (right != null) right->print(); } main() { if (root != null) root->print(); cout << endl; } 1 2 3

Chakrabarti Adding a parent pointer  Walking down from parent to child is easy  Sometimes handy to be able to walk up from child to parent as well, e.g., to find siblings  root->up is null struct TreeNode { const int key; TreeNode *left, *right, *up; TreeNode(int _key, TreeNode *_up) : key(_key), up(_up) { left = right = null; } void insert(int nKey) { … } };

Chakrabarti Constant pointer vs. pointer to constant  Suppose we want the up pointer to be constant  This is declared as TreeNode * const up;  Content of TreeNode can change  A pointer to a constant TreeNode would be const TreeNode * up;  Not the same!  Can also have const TreeNode * const up;

Chakrabarti Pointers vs. references int a = 3, b = 5; int *px = &a; px = &b; // above statements do not // change values in cells // called a and b int &rx = a; rx = b; // this results in a = b = 5

Chakrabarti Multiple pointers to one record  Generally necessary in applications  E.g., fixed deposit accounts and checking accounts pointing to shared customer record  Care is needed in destructors  Deleting a checking account should not destroy a customer record  Should deleting the last account of a customer delete the customer record?  Clear “home” collection whose destruction deletes customer record