COP 3330 Object-oriented Programming in C++

Slides:



Advertisements
Similar presentations
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Advertisements

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.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
Object Oriented Programming COP3330 / CGS5409.  Dynamic Allocation in Classes  Review of CStrings.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Runtime Environments Compiler Construction Chapter 7.
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.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Pointers OVERVIEW.
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More C++ Features True object initialisation
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Object Oriented Programming COP3330 / CGS5409.  Aggregation / Composition  Dynamic Memory Allocation.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 220 – C Programming malloc, calloc, realloc.
Memory Management.
Dynamic Storage Allocation
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Cinda Heeren / Geoffrey Tien
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Dynamic Memory Allocation
Motivation and Overview
Andy Wang Object Oriented Programming in C++ COP 3330
Object Oriented Programming COP3330 / CGS5409
Pointers and Memory Overview
Pointers Revisited What is variable address, name, value?
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
This pointer, Dynamic memory allocation, Constructors and Destructor
Andy Wang Object Oriented Programming in C++ COP 3330
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
CMSC 341 Prof. Michael Neary
An Introduction to Pointers
Automatics, Copy Constructor, and Assignment Operator
Object Oriented Programming COP3330 / CGS5409
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Automatics, Copy Constructor, and Assignment Operator
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Memory Allocation CS 217.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Given the code to the left:
Dynamic Memory A whole heap of fun….
Arrays an array of 5 ints is filled with 3,2,4,1,7
9-10 Classes: A Deeper Look.
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Run Time Environments 薛智文
Recitation Course 0603 Speaker: Liu Yu-Jiun.
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Presentation transcript:

COP 3330 Object-oriented Programming in C++ Dynamic Memory Allocation Spring 2019

Memory Allocation Static (compile time) memory allocation Memory for the named variables is allocated by the compiler in stacks The exact size and type of storage must be known a priori The size of an array has to be constant Dynamic memory allocation Memory allocated during runtime is placed in a program segment known as the heap The compiler does not need to know the exact size and number of items to be allocated Pointers are crucial

Stack Special region of computer memory that stores temporary variables in each function Every time a function declares a new variable, it is "pushed" onto the stack Every time a function exits, all of the variables pushed onto the stack by that function, are “popped" (freed, and hence lost forever) A common bug in C++ programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited)

Stack #include <iostream> using namespace std; double multiplyByTwo (double input) { double twice = input * 2.0; return twice; } int main () int age = 30; double salary = 12345.67; double myList[3] = {1.2, 2.3, 3.4}; cout << "double your salary is “ << multiplyByTwo(salary)) << endl; return 0;

Heap A more free-floating region of memory (and is larger) that is not managed automatically for you Use new and delete to manage heap memory Caution: memory leak! Use pointers to access memory on the heap a special data type that stores addresses in memory instead of storing actual values No size restrictions on variable size (apart from the obvious physical limitations of your computer) Variables created on the heap are accessible by any function, anywhere in your program Heap variables are essentially global in scope

Heap #include <iostream> double *multiplyByTwo (double *input) { double *twice = new double; *twice = *input * 2.0; return twice; } int main () int *age = new int; *age = 30; double *salary = new double; *salary = 12345.67; double *myList = new double [3]; myList[0] = 1.2; myList[1] = 2.3; myList[2] = 3.4; double *twiceSalary = multiplyByTwo(salary); delete age; delete salary; delete[] myList; delete twiceSalary; return 0;

Stack vs. Heap Stack Space is managed efficiently by CPU, memory will NOT become fragmented Grows and shrinks as functions push and pop local variables NO need to manage the memory yourself, variables are allocated and freed automatically Very fast access Has size limits (OS-dependent) Stack variables only exist while the function that created them is running Variables cannot be resized

Stack vs. Heap Heap Variables can be accessed globally NO limit on memory size Variables can be resized (Relatively) Slower access No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed You must manage memory (you're in charge of allocating and freeing variables)

Dynamic Memory Allocation Can allocate memory at run time But, cannot create new variables names at run time Thus, there are two steps in dynamic allocation Allocate the space use the unary operator, new, followed by the type being allocated new returns the starting address of the allocated space Store its address in a pointer (so that the space can be accessed) int* p = new int; int size = 40; // dynamically allocates an array of 40 ints int * list = new int[size]; float* numbers = new float[size+10];

Dynamic Memory Access For single items, dereference the pointer to reach a dynamically created target, using the * operator For dynamically created arrays, you can use either pointer-offset notation, or standard bracket notation int *p = new int; *p = 10; // assigns 10 to the dynamic integer cout << *p; // prints 10 double *numList = new double[size]; for (int i = 0; i < size; i++) numList[i] = 0; numList[5] = 20; *(numList + 7) = 15; // same as numList[7]

Dynamic Memory Deallocation Free up the dynamically allocated space by programmers when it is of no use Use the unary operator, delete Note that the name ptr can be reused To deallocate a dynamic array, use this form delete[] name_of_pointer We do not want list to point to deallocated memory space int *ptr = new int; delete ptr; // free up the space pointed by ptr ptr = new int[10]; int *list = new int[40]; delete[] list; // deallocate the array list = 0; // reset the pointer to null

Memory Leak You fail to deallocate dynamically allocated memory… list = new int[40]; // first allocation // no deallocation // ………… // you forgot to delete[] list list = new int[10]; // second allocation

Dynamically Resizing I created an array with an initial size of , say, 100. Later on, I recognize that 100 is not sufficient, and I wanna resize the array with a larger size. How? int *list = new int[size]; // create a bigger temp array int *temp = new int[2*size]; // item-wise copy for (int i = 0; i < size; i++) temp[i] = list[i]; delete [] list; // free up the old memory // make list point to the new memory location list = temp;

Dynamically Resizing list Item-wise copy temp list

Dynamic Allocation of Objects Objects can be dynamically allocated as well To deallocate Fraction *fp1, *fp2, *flist; // uses default constructor fp1 = new Fraction; fp2 = new Fraction(3,4); // flist is dynamic array of 20 Fraction objects with default constructor for each flist = new Fraction[20]; delete fp1; delete fp2; delete [] flist;

Dot Operator (.) cs. Arrow Operator (->) A dot operator requires an object name objectName.memberName // can be data or function An arrow operator works with object pointers objectPointer->memberName // data or function You need to dereference an object pointer before using the dot operator (*fp1).show(); For pointers to dynamically allocated arrays of objects, arrow operator usually is not needed flist[3].show(); // flist is a pointer; flist[3] is an object flist[3]->show(); // INCORRECT

Dynamic Memory Allocation in Classes A motivation scenario Suppose we want an array as a member data Don’t want a fixed upper bound on the size Real-world examples: shopping transactions in Walmart; visit traces on youtube.com; query logs on Google …… Solution Only embed the array pointer in classes Declare array pointers as member data Always initialize pointers in the constructors The constructor might dynamically allocate spaces (via new) and assign them to pointers The array dynamically grows (or shrinks) adaptively Cleanup (via delete) dynamically allocated space in destructor Can happen in regular member functions

Code Review: the PhoneBook Database Entry Class Represents a single entry in a phone book Uses c-strings (null-terminated character arrays) to store names, addresses, and phone numbers Directory class Stores an array of Entry objects in a dynamic fashion Provides services add, delete, modify, search, and display entries Dynamically resize the array of Entries

More Details in PhoneBook In Entry class, we overload << and >> Use getline()to get a string containing spaces (up to newline) In Directory class, we grow entrylist if necessary void Directory::growBad() { maxSize = currentSize + 5; Entry newList[maxSize]; for (int j = 0; j < currentSize; j++) newList[j] = entryList[j]; delete [] entryList; entryList = newList; }

Questions