Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Dynamic Memory

2 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 and delete expressions First we will cover Sect 5.11. The new and delete expressions Then we will cover Sect. 4.3.1. Dynamically allocating arrays Then we will cover Sect. 4.3.1. Dynamically allocating arrays

3 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

4 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

5 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 "9999999999" string s(10, '9'); // value of s is "9999999999" string *ps = new string(10, '9'); // *ps is //"9999999999“ string *ps = new string(10, '9'); // *ps is //"9999999999“ 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

6 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

7 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

8 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

9 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

10 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

11 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.

12 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.

13 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

14 Link list program See newdelete.cpp See newdelete.cpp

15 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.

16 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.


Download ppt "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."

Similar presentations


Ads by Google