Dynamic Allocation Eric Roberts CS 106B February 4, 2013.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
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.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Lecture 9 Concepts of Programming Languages
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS-2303 System Programming Concepts
IT PUTS THE ++ IN C++ Object Oriented Programming.
Review of C++ Programming Part II Sheng-Fang Huang.
Memory and C++ Eric Roberts CS 106B February 1, 2013.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 7 Objects and Memory. Structure of memory The fundamental unit of memory is called a bit, either 0 or 1. In most modern architectures, the smallest.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 7—Objects and Memory The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Memory C H A P T E R 7 Yea, from.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
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++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Object-Oriented Programming in C++
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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:
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Data Representation Eric Roberts CS 106A February 10, 2016.
Chapter 5 (Part 1) ADT Stack 1 Fall Stacks TOP OF THE STACK.
Implementing Queues Eric Roberts CS 106B February 13, 2013.
Memory Management.
Constructors and Destructors
Pointers and Linked Lists
Pointers and Linked Lists
Editor Buffers Eric Roberts CS 106B February 6, 2013.
Objects and Memory Eric Roberts CS 106A February 5, 2010.
Pointers and Dynamic Variables
Pointers and Linked Lists
Lecture 9 Concepts of Programming Languages
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9 Classes: A Deeper Look, Part 1
Pointers and Linked Lists
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 7—Objects and Memory
Recitation Course 0603 Speaker: Liu Yu-Jiun.
C++ Plus Data Structures
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
COP 3330 Object-oriented Programming in C++
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
More C++ Classes Systems Programming.
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Dynamic Allocation Eric Roberts CS 106B February 4, 2013

The Allocation of Memory to Variables When you declare a variable in a program, C++ allocates space for that variable from one of several memory regions. One region of memory is reserved for variables that persist throughout the lifetime of the program, such as constants. This information is called static data. static data 0000 stack FFFF Each time you call a method, C++ allocates a new block of memory called a stack frame to hold its local variables. These stack frames come from a region of memory called the stack. It is also possible to allocate memory dynamically, as described in Chapter 12. This space comes from a pool of memory called the heap. heap In classical architectures, the stack and heap grow toward each other to maximize the available space.

Dynamic Allocation C++ uses the new operator to allocate memory on the heap. You can allocate a single value (as opposed to an array) by writing new followed by the type name. Thus, to allocate space for a int on the heap, you would write int *ip = new int; int *array = new int[10000]; You can allocate an array of values using the following form: new type [ size ] Thus, to allocate an array of integers, you would write: The delete operator frees memory previously allocated. For arrays, you need to include empty brackets, as in delete[] array;

Exercise: Dynamic Arrays Write a method createIndexArray(n) that returns an integer array of size n in which each element is initialized to its index. As an example, calling int *digits = createIndexArray(10); should result in the following configuration: digits How would you free the memory allocated by this call?

pt FFFC FFF8 FFF4 3 4 Allocating a Point Object The usual way to allocate a Point object is to declare it as a local variable on the stack, as follows: Point pt(3, 4); It is, however, also possible to allocate a Point object on the heap using the following code: Point *pp = new Point(5, 12); pp FFFC FFF pp 5 12

The -> Operator In C++, pointers are explicit. Given a pointer to an object, you need to dereference the pointer before selecting a field or calling a method. Given the definition of pp from the previous slide, you cannot write pp.getX() because pp is not a structure. You also cannot write *pp.getX() because. takes precedence over *. To call a method given a pointer to an object, you need to write pp->getX()

The Keyword this In the implementation of the methods within a class, you can usually refer to the private instance variables of that class using just their names. C++ resolves such names by looking for matches in each of the following categories: –Parameters or local variables declared in the current method –Instance variables of the current object –Global variables defined in this scope It is often convenient to use the same names for parameters and instance variables. If you do, you must use the keyword this (defined as a pointer to the current object) to refer to the instance variable, as in the constructor for the Point class: Point::Point(int x, int y) { this->x = x; this->y = y; }

Memory Management The big challenge in working with dynamic allocation is freeing the heap memory you allocate. Programs that fail to do so have what computer scientists call memory leaks. In Java, objects are created on the heap and are automatically reclaimed by a garbage collector when those objects are no longer accessible. This discipline makes memory management very easy and convenient. In C++, the situation is different for the following reasons: –Objects can be allocated either on the stack or in the heap. –C++ has no garbage collector, which means that programmers must manage memory allocation explicitly. Fortunately, the designers of C++ made it possible to free memory allocated by objects when those objects go out of scope on the stack....

Destructors In C++, class definitions often include a destructor, which specifies how to free the storage used to represent an instance of that class. The prototype for a destructor has no return type and uses the name of the class preceded by a tilde ( ~ ). The destructor must not take any arguments. C++ calls the destructor automatically whenever a variable of a particular class is released. For stack objects, this happens when the function returns. The effect of this rule is that a C++ program that declares its objects as local variables on the stack will automatically reclaim those variables. If you instead allocate space for an object in the heap using new, you must explicitly free that object by calling delete. Calling delete automatically invokes the destructor.

The CharStack Class CharStack cstk; Initializes an empty stack. cstk.size() Returns the number of characters pushed onto the stack. cstk.isEmpty() Returns true if the stack is empty. cstk.clear() Deletes all characters from the stack. cstk.push(ch) Pushes a new character onto the stack. cstk.pop() Removes and returns the top character from the stack.

/* * File: charstack.h * * This interface defines the CharStack class. */ #ifndef _charstack_h #define _charstack_h class CharStack { public: /* * CharStack constructor and destructor * * The constructor initializes an empty stack. The destructor * is responsible for freeing heap storage. */ CharStack(); ~CharStack(); The charstack.h Interface

/* * File: charstack.h * * This interface defines the CharStack class. */ #ifndef _charstack_h #define _charstack_h class CharStack { public: /* * CharStack constructor and destructor * * The constructor initializes an empty stack. The destructor * is responsible for freeing heap storage. */ CharStack(); ~CharStack(); /* * Methods: size, isEmpty, clear, push, pop * * These methods work exactly as they do for the Stack class. * The peek method has been eliminated to save space. */ int size(); bool isEmpty(); void clear(); void push(char ch); char pop(); The charstack.h Interface

/* * Methods: size, isEmpty, clear, push, pop, peek * * These methods work exactly as they do for the Stack class. */ int size(); bool isEmpty(); void clear(); void push(char ch); char pop(); char peek(); /* Private section */ private: /* Private constants */ static const int INITIAL_CAPACITY = 10; /* Instance variables */ char *array; /* Dynamic array of characters */ int capacity; /* Allocated size of that array */ int count; /* Current count of chars pushed */ /* Private function prototype */ void expandCapacity(); }; #endif The charstack.h Interface

/* * File: charstack.cpp * * This file implements the CharStack class. */ #include "charstack.h" #include "error.h" using namespace std; /* Constructor and destructor */ CharStack::CharStack() { capacity = INITIAL_CAPACITY; array = new char[capacity]; count = 0; } CharStack::~CharStack() { delete[] array; } The charstack.cpp Implementation

/* * File: charstack.cpp * * This file implements the CharStack class. */ #include "charstack.h" #include "error.h" using namespace std; /* Constructor and destructor */ CharStack::CharStack() { capacity = INITIAL_CAPACITY; array = new char[capacity]; count = 0; } CharStack::~CharStack() { delete[] array; } int CharStack::size() { return count; } bool CharStack::isEmpty() { return count == 0; } void CharStack::clear() { count = 0; } void CharStack::push(char ch) { if (count == capacity) expandCapacity(); array[count++] = ch; } char CharStack::pop() { if (isEmpty()) error("pop: Stack is empty"); return array[--count]; } The charstack.cpp Implementation

int CharStack::size() { return count; } bool CharStack::isEmpty() { return count == 0; } void CharStack::clear() { count = 0; } void CharStack::push(char ch) { if (count == capacity) expandCapacity(); array[count++] = ch; } char CharStack::pop() { if (isEmpty()) error("pop: Stack is empty"); return array[--count]; } /* * Implementation notes: expandCapacity * * This private method doubles the capacity of the elements array * whenever it runs out of space. To do so, it must copy the * pointer to the old array, allocate a new array with twice the * capacity, copy the characters from the old array to the new * one, and finally free the old storage. */ void CharStack::expandCapacity() { char *oldArray = array; capacity *= 2; array = new char[capacity]; for (int i = 0; i < count; i++) { array[i] = oldArray[i]; } delete[] oldArray; } The charstack.cpp Implementation

Heap-Stack Diagrams It is easier to understand how C++ works if you have a good mental model of its use of memory. I find the most useful model is a heap-stack diagram, which shows the heap on the left and the stack on the right, separated by a dotted line. Whenever your program uses new, you need to add a block of memory to the heap side of the diagram. That block must be large enough to store the entire value you’re allocating. If the value is a struct or an object type, that block must include space for all the members inside that structure. Whenever your program calls a method, you need to create a new stack frame by adding a block of memory to the stack side. For method calls, you need to add enough space to store the local variables for the method, again with some overhead information that tracks what the program is doing. When a method returns, C++ reclaims the memory in its frame.

Exercise: Heap-Stack Diagrams heap stack int main() { Point pt; double total = 0.0; pt.x = 1; pt.y = 2; int *array = new int[5]; nonsense(array, pt, total); return 0; } stack total pt FFFC FFF8 FFF4 FFF0 FFEC FFE8 array ??? C 1010 ??? total & pt FFE4 FFE0 FFDC FFD8 FFD4 list FFF4 pptr ??? FFD ??? void nonsense(int list[], Point pt, double & total) { Point *pptr = new Point; list[1] = pt.x; total += pt.y; }

The End

pt FFFC FFF8 FFF4 3 4 Allocating a Point Object The usual way to allocate a Point object is to declare it as a local variable on the stack, as follows: Point pt(3, 4); It is, however, also possible to allocate a Point object on the heap using the following code: Point *pp = new Point(5, 12); pp FFFC FFF pp 5 12