CISC/CMPE320 - Prof. McLeod

Slides:



Advertisements
Similar presentations
Winter 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assn 4 posted shortly. Demonstrate a memory leak problem using the assignment 4 solution. Back to.
Advertisements

Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
Ch 4. Memory Management Timothy Budd Oregon State University.
Stack and Heap Memory Stack resident variables include:
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). SDD document framework should be set up in your Wiki by now.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
Learners Support Publications Constructors and Destructors.
Memory Management.
Constructors and Destructors
Object Lifetime and Pointers
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Memory Management with Classes
Overview 4 major memory segments Key differences from Java stack
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Lesson One – Creating a thread
Motivation and Overview
Pointers, Polymorphism, and Memory Allocation
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Pointers and References
This pointer, Dynamic memory allocation, Constructors and Destructor
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
CISC/CMPE320 - Prof. McLeod
Advanced Programming Behnam Hatami Fall 2017.
Dynamically Allocated Memory
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
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
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Given the code to the left:
Constructors and Destructors
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Fall 2018 CISC124 2/22/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. The prof. (me!) will start grading the quiz.
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Objects Managing a Resource
Arrays an array of 5 ints is filled with 3,2,4,1,7
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Java Programming Language
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Winter 2019 CMPE212 5/10/2019 CMPE212 – Reminders
CISC/CMPE320 - Prof. McLeod
CMPE212 – Reminders Assignment 2 due next Friday.
Classes and Objects Object Creation
SPL – PS2 C++ Memory Handling.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CISC/CMPE320 - Prof. McLeod Winter 2013 CISC/CMPE320 2/24/2019 CISC/CMPE320 SDD “Due” this Friday evening – Nov. 2 in Confluence. Assignment 3 is now due Nov. 6 (next Tuesday). Fall 2018 CISC/CMPE320 - Prof. McLeod Prof. Alan McLeod

CISC/CMPE320 - Prof. McLeod Today Using the Heap, Cont. Not Using the Heap Properly – Common Memory Errors. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Back to C++ We were talking about using the heap: The new and new[] operators provide “dynamic memory allocation”. These operators return a pointer to memory allocated on the heap. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Using the Heap Advantages: The size of the memory to be allocated does not have to be known until run-time. Once allocated the memory persists until either the program completes or you free up the memory by issuing a delete or delete[] on the pointer. You can return a pointer to this memory from a function and it will remain stable. The available memory is huge – determined really by the amount of RAM on your system (and whether or not you are using a 32 bit compiler). Much more memory than what is available on the stack. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Using the Heap, Cont. Disadvantages: The responsibility for maintaining the heap is given to the coder (a human!!, very human sometimes!!) As we will see, forgetting to remove something from the heap can lead to the dreaded and very common “memory leak” problem. Crash, crash, crash! For example: Fall 2018 CISC/CMPE320 - Prof. McLeod

Notes on Using new[] and delete[], Cont. Suppose you do something like: string** arr = new string*[100]; for(int i=0; i < 100; i++) arr[i] = new string(); Will this be enough to delete this structure completely?: delete[] arr; Fall 2018 CISC/CMPE320 - Prof. McLeod

Notes on Using new[] and delete[], Cont. Similarly: vector<string*> *varr = new vector<string*>(); for (int i = 0; i < 100; i++) varr->push_back(new string()); Will this be enough to delete this structure completely?: delete varr; Fall 2018 CISC/CMPE320 - Prof. McLeod

Class Attributes on the Heap You can reduce the risk by following some standard coding rules when the heap is used by your class to store an attribute. For example, you can write the code that is responsible for cleaning up the heap in a special function called the Destructor: Fall 2018 CISC/CMPE320 - Prof. McLeod

Destructor Member Function Distinguished from a constructor using the ~ before the class name. Responsible for deleting all heap variables (using delete and delete[]). If you use the heap in your class you must have a destructor. You never invoke the destructor directly – the system will invoke it instead. Back to our collection of strings: Fall 2018 CISC/CMPE320 - Prof. McLeod

Example of Code in a Destructor To clean up the previous example: for (int i = 0; i < 100; i++) delete varr.at(i); delete varr; varr = nullptr; The destructor is a member of a group of functions called “The Big Three”: Fall 2018 CISC/CMPE320 - Prof. McLeod

“The Big Three” – Summary Destructor: Frees all heap memory used by the object. Copy constructor: Initializes the object as a copy of the same type object supplied as a parameter. If you are using heap memory you will need to allocate and initialize each value. Assignment operator: Check to make sure that you are not assigning yourself. If so, do nothing. Free up the heap memory that is no longer needed. Copy the value of the argument supplied. Return *this. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Aside - “The Big Three” Any class that uses the heap must have these three functions. More on these guys later. We will build them in a demo program. And we have to learn about when these functions are invoked. For now, let’s summarize some common errors created by the improper use of memory in C++. Using the heap makes it much easier for the coder to create errors! Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Common Memory Errors Using a variable that has not been initialized. Using a pointer to reference a memory location that is no longer valid. Forgetting to delete something on the heap. Deleting a memory value that was never allocated. Deleting something on the heap more than once. Look at each of these, in turn: Fall 2018 CISC/CMPE320 - Prof. McLeod

Initialization Memory Errors We’ve seen this one before. A variable or pointer is created, but not initialized. Includes creating an array on the heap, but not initializing its elements. You don’t get an error, you just get some random value – whatever happens to be in that memory location. Fall 2018 CISC/CMPE320 - Prof. McLeod

Lifetime Memory Errors When an activation record is popped off the run-time stack it takes all its local variables with it – they are no longer valid. If you have returned a pointer or a reference to a local variable, that location will only be valid until the next function invocation occurs. It is likely that this location will be overwritten. Eventually. Fall 2018 CISC/CMPE320 - Prof. McLeod

Lifetime Memory Errors, Cont. For example: char* readALine() { char buffer[200]; cin >> buffer; return buffer; } char* p = readALine(); p is called a “dangling pointer” as it is pointing to memory that is no longer valid after readALine() is finished. Fall 2018 CISC/CMPE320 - Prof. McLeod

Aside – Buffer Overflow Error Consider that readALine() function again: Suppose the user entered more than 200 characters: In this case, the extra characters would end up being written to memory beyond the dimensions of the array. This used to be a popular way for virus writers to inject their own function into an application. If you can overwrite the return address of the activation frame to the address of your function… Fall 2018 CISC/CMPE320 - Prof. McLeod

Lifetime Memory Errors, Cont. You can cause similar behaviour if you attempt to return a reference to a local variable. For example: Fraction& operator+(const Fraction& left, const Fraction& right) { Fraction result(left.numer() * right.denominator() + right.numer() * left.denominator(), left.denominator() * right.denominator()); return result; } Get rid of this Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Memory Leaks When you forget to delete something on the heap. More likely to cause a problem in a long-running program. Suppose you have successive re-assignments to the same pointer variable inside a loop. If you don’t carry out a delete in-between assignments each object remains on the heap. Eventually the heap manager will be unable to service any new allocation requests. Fall 2018 CISC/CMPE320 - Prof. McLeod

Invalid Memory References What happens when you are too eager to delete a value from the heap. If you have more than one pointer aliased to that value, then the second pointer becomes invalid. For example, deleting the nodes of a linked list in a for loop: for (Node* p = ptr; p != NULL; p = p->next) delete p; } p->next is no longer accessible after deletion. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Aside – Using nullptr You can assign a pointer to be nullptr. (It does not happen by default as in Java!). Deleting a null pointer has no effect. So, consider setting a pointer to nullptr after you have deleted it: This will prevent you trying to invoke any functions from the pointer (you will get a null pointer error). And if you do try to delete the pointer again, nothing bad will happen. Fall 2018 CISC/CMPE320 - Prof. McLeod

Deleting an Un-Initialized Pointer Fraction* frac; delete frac; Bad news. You are trying to delete garbage. Better to set to nullptr if you cannot initialize right away: Fraction* frac = nullptr: Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Object Slicing Another memory problem that is particular to C++. For example: Child* c = new Child(arguments…); Parent* p = c; // OK Parent pp = *c; // NOT OK This is legal, compiles and runs fine, but what is the problem with the last line? Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Object Slicing, Cont. The portion of the Child object that will not fit into an object of type Parent is “sliced” away – it is lost, when the pointer, c, is de-referenced. This is one of the reasons why it is best to access objects through pointers or references only. Fall 2018 CISC/CMPE320 - Prof. McLeod

Polymorphism – Peeking… A dynamic cast can be used to determine what kind of object you actually have. If the cast fails a nullptr is returned. For example: Child* c = dynamic_cast<Child*>(object); c will be nullptr if object is not a Child or a parent of Child. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Peeking, Cont. Note that a static_cast<Child> will not check to see if the type will work. You don’t get a nullptr, you just get a problem… It is best to just use static_cast<type> with primitive types only. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod “The Big Three” Again… Destructor: Frees all heap memory used by the object. Copy constructor: Initializes the object as a copy of the same type object supplied as a parameter. If you are using heap memory you will need to allocate and initialize each value. Assignment operator: Check to make sure that you are not assigning yourself. If so, do nothing. Free up the heap memory that is no longer needed. Copy the value of the argument supplied. Return *this. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Destructor Sounds sinister! If you have any attributes that use the heap, you must have a destructor that cleans them up: MyString::~MyString() { delete[] buffer; buffer = nullptr; } Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Destructor, Cont. Invoked: For any local variables when execution reaches the end of the block in which they are declared. For any arguments when the end of the function is reached. Any temporary (named or unnamed) variables used in a statement when the statement is complete. If a variable stored on the heap is deleted (using delete). For all global and local static variables when main completes. When an object is deleted, for all attributes in the object. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Destructor, Cont. Invoked, cont.: When an object from a derived (child) class is deleted, for all attributes in the base (parent) class. (Aside – the destructor must be declared virtual. More later…) When an exception is thrown and, as a result, execution leaves the current block of code. If you don’t write your own destructor the system-generated one is just an empty destructor – rather useless… Only needed if any of your attributes use heap memory. Prevents memory leaks. Fall 2018 CISC/CMPE320 - Prof. McLeod

Aside – Deletion vs. Destruction Deletion occurs when a pointer is passed to the delete operator. Destruction occurs whenever the destructor is invoked. A pointer is deleted, an object is destroyed. (Remember to set a pointer variable to nullptr after you have deleted it…) Fall 2018 CISC/CMPE320 - Prof. McLeod

MyString Class Example Adapted from “Big C++” by Horstmann and Budd: Background: A “C-string” is just an array of char. A string literal will be stored on the stack. However the STL class string stores string contents on the heap, which simplifies any operation that changes the length of the string. Build our own class, MyString, which behaves like an abbreviated version of the STL class string. Mostly because it uses the heap. Fall 2018 CISC/CMPE320 - Prof. McLeod

Constructors – Overview Not just a copy constructor: Default constructor. Conversion constructors. Parameterized constructors. And, when do constructors (and destructors) get called? This is important, since you cannot make an explicit call to any constructor or the destructor. Fall 2018 CISC/CMPE320 - Prof. McLeod

MyString Class Constructors MyString(); // Default constructor MyString(const char[]); // Simple constructor MyString(const MyString&); // Copy constructor MyString(int); // Conversion constructor Called when: Execution enters a block in which a MyString is declared. A variable of type MyString is placed on the stack. A global variable of type MyString is declared. The variable is placed in the globals memory before main starts. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Constructors, Cont. Called when, cont: A static local variable of type MyString is declared. The variable is placed in global memory before main starts. Whenever new MyString is invoked. The variable is created on the heap and the memory address stored in a pointer on the stack. An unnamed temporary variable is created to hold the return value of a function when it is of type MyString. An object is constructed that has an attribute of type MyString. A variable of a type extended from MyString is created. The constructor of the parent class is invoked by the constructor of the child class (no choice). Fall 2018 CISC/CMPE320 - Prof. McLeod

MyString Class Constructors, Cont. Can be invoked with: No argument at all (the default constructor). A string literal like “Hello!” (the simple constructor). An integer value (the conversion constructor). Another MyString (the copy constructor). Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Copy Constructor MyString::MyString(const MyString& right) { len = right.length(); buffer = new char[len + 1];// Using heap for (int i = 0; i < len; i++) buffer[i] = right[i]; buffer[len] = '\0'; } Creates a copy or clone of the supplied argument. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Copy Constructor, Cont. Invoked when: The MyString constructor is supplied with a MyString type argument. When you assign one MyString to another using =. When a MyString is passed into a function as a value parameter (not as a reference – but it is better to pass a const reference…). The cloning carried out by the copy constructor prevents aliasing in these situations. Fall 2018 CISC/CMPE320 - Prof. McLeod

CISC/CMPE320 - Prof. McLeod Copy Constructor, Cont. If you don’t write your own copy constructor, you get a system-defined copy constructor that carries out a simple, memberwise copy for each attribute in an object. In the case of an attribute stored on the heap, you can get multiple stack variables pointing (or aliased) to the same area of the heap – probably not what you want. Not a “deep copy” or “clone”, but more like a “shallow copy”. Fall 2018 CISC/CMPE320 - Prof. McLeod