Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect 5.11. The new.

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

Chapter 6 Data Types
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
1 Pointers (Walls & Mirrors - Beginning of Chapter 4)
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
Dynamic Objects. COMP104 Lecture 31 / Slide 2 Static verses Dynamic Objects * Static object n Memory is acquired automatically  int A[10]; n Memory is.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Stack and Heap Memory Stack resident variables include:
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
C++ Memory Overview 4 major memory segments Key differences from Java
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
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.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
C Programming Lecture 16 Pointers. Pointers b A pointer is simply a variable that, like other variables, provides a name for a location (address) in memory.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Revision on C++ Pointers TCP1201: 2013/2014. Pointer Basics  Why pointer is important? 1. Reference/Point to existing data without cloning the data.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Introduction to Object Oriented Programming Chapter 10.
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.
P OINTERS A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory.
Pointer Data Type and Pointer Variables III CS1201: Programming Language 2 By: Nouf Aljaffan Edited by : Nouf Almunyif.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Inheritance - 3. Virtual Functions Functions defined as virtual are ones that the base expects its derived classes may redefine. Functions defined as.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers and Arrays Dynamic Variables and Arrays.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Note: Some of the slides are repeated from Introduction to C++
C++ Exceptions.
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Introduction to Pointers and Dynamic Memory Allocation
C++ Standard Library.
Pointers and Memory Overview
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
Dynamic Memory.
C++ Introduction - 3.
Std Library of C++.
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Dynamic Memory

We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new and delete expressions First we will cover Sect The new and delete expressions Then we will cover Sect Dynamically allocating arrays Then we will cover Sect Dynamically allocating arrays

Dynamic memory … C++ allows us to allocate dynamic memory C++ allows us to allocate dynamic memory C uses malloc and free C uses malloc and free C++ uses new and delete C++ uses new and delete Dynamic memory is referred to as: Dynamic memory is referred to as: Heap or Heap or Free store Free store Automatic variables do NOT use dynamic memory. The memory they use is called: Automatic variables do NOT use dynamic memory. The memory they use is called: Stack Stack

new int i; // named, uninitialized int variable int i; // named, uninitialized int variable int *pi = new int; // pi points to dynamically int *pi = new int; // pi points to dynamically // allocated, unnamed, uninitialized // allocated, unnamed, uninitialized // int new is an expression in C++ (as against malloc() which is a function call) new is an expression in C++ (as against malloc() which is a function call) new expression returns a pointer to the newly allocated object. new expression returns a pointer to the newly allocated object. We use the returned pointer to access the object. We use the returned pointer to access the object. *pi = 2;//Makes int on heap pointed to by pi 2; *pi = 2;//Makes int on heap pointed to by pi 2; cout << *pi << endl;// Will print 2 cout << *pi << endl;// Will print 2

Initialization of Dynamic objects int i(1024); // value of i is 1024 int i(1024); // value of i is 1024 int *pi = new int(1024); // object to which pi int *pi = new int(1024); // object to which pi // points is 1024 string s(10, '9'); // value of s is " " string s(10, '9'); // value of s is " " string *ps = new string(10, '9'); // *ps is //" “ string *ps = new string(10, '9'); // *ps is //" “ New initialization can be done only using direct- initialization syntax i.e. (…) New initialization can be done only using direct- initialization syntax i.e. (…) Cannot use copy initialization syntax Cannot use copy initialization syntax Int *pi = new int = 1024; // Error Int *pi = new int = 1024; // Error

Default initialization Same way as for automatic variables (variables defined inside a function) Same way as for automatic variables (variables defined inside a function) If object is class type then default constructor is called. If object is class type then default constructor is called. string *ps = new string; // initialized to empty //string string *ps = new string; // initialized to empty //string If object is built-in type it is uninitialized If object is built-in type it is uninitialized int *pi = new int; // pi points to an uninitialized int int *pi = new int; // pi points to an uninitialized int

Value initialization For built-in types For built-in types int *pi = new int; // pi points to an uninitialized int int *pi = new int; // pi points to an uninitialized int int *pi = new int(); // pi points to an int value- int *pi = new int(); // pi points to an int value- //initialized to 0 Using empty parentheses invokes value initialization. Using empty parentheses invokes value initialization. For class types using empty parentheses invokes default constructor For class types using empty parentheses invokes default constructor string *ps = new string(); string *ps = new string(); // initialized to empty string So value initialization is not significant for class types So value initialization is not significant for class types

Freeing memory delete expression is used to return dynamic memory allocated by new to Free Store delete expression is used to return dynamic memory allocated by new to Free Store int *pi = new int(); // pi points to an int value- int *pi = new int(); // pi points to an int value- //initialized to 0 *pi = 25; *pi = 25; … delete pi; //Returns memory pointed to delete pi; //Returns memory pointed to //by pi to Free Store

delete … Cannot use delete with memory not allocated by new. Cannot use delete with memory not allocated by new. Memory allocated by malloc() must be freed by free() only and not delete Memory allocated by malloc() must be freed by free() only and not delete

delete … int i; int i; int *pi = &i; int *pi = &i; string str = "dwarves"; string str = "dwarves"; double *pd = new double(33); double *pd = new double(33); delete str; // error: str is not a dynamic object delete str; // error: str is not a dynamic object delete pi; // error: pi refers to a local delete pi; // error: pi refers to a local delete pd; // ok delete pd; // ok

delete of Zero Valued Pointer Legal to delete pointer equal to 0 Legal to delete pointer equal to 0 int *ip = 0; int *ip = 0; delete ip; // ok: always ok to delete a pointer delete ip; // ok: always ok to delete a pointer // that is equal to 0 // that is equal to 0 Nothing will happen for above statement Nothing will happen for above statement Language guarantees that delete of a pointer with value 0 is safe. Language guarantees that delete of a pointer with value 0 is safe.

Resetting value of pointer after delete int *p = new int(); int *p = new int(); delete p; delete p; After above statement p’s value is undefined After above statement p’s value is undefined p may still have address of old object which is now destroyed p may still have address of old object which is now destroyed P is now called as a dangling pointer P is now called as a dangling pointer Using p may result in unpredictable behaviour Using p may result in unpredictable behaviour Very difficult to track bugs can be caused. Very difficult to track bugs can be caused.

Resetting value of pointer after delete … To avoid this, safe programming is to reset value of delete pointer to 0. To avoid this, safe programming is to reset value of delete pointer to 0. int *p = new int(); int *p = new int(); delete p; delete p; p = 0; p = 0; Now repeating delete p will be safe Now repeating delete p will be safe Access of data pointed to by p will definitely fail Access of data pointed to by p will definitely fail Failure but predictable failure Failure but predictable failure As against unpredictable success or failure if p is not set to 0 As against unpredictable success or failure if p is not set to 0 Former is much more preferrable Former is much more preferrable Latter can cause very hard to track bugs Latter can cause very hard to track bugs

Link list program See newdelete.cpp See newdelete.cpp

Assignments Write small programs which use new and delete trying out all examples shown so far. Write small programs which use new and delete trying out all examples shown so far. OPTIONAL: If time permits, write the linked list program shown earlier. OPTIONAL: If time permits, write the linked list program shown earlier. For these assignments there will be no submission For these assignments there will be no submission Objective is to simply give you some hands-on familiarity with new and delete. Objective is to simply give you some hands-on familiarity with new and delete. Proper assignment for new and delete will be given later on. Proper assignment for new and delete will be given later on.

Book Source Code Copyright Note The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides. The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides.