1 / 80

Dynamic Memory Management

Dynamic Memory Management. Static Memory Management, limitations, Dynamic Memory Management Mechanism, use of new and delete operators, Methods for allocating and deallocating memory for single objects and array of objects, use of set_new_handler function to slide-25specify our own handler.

opal
Télécharger la présentation

Dynamic Memory Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dynamic Memory Management Static Memory Management, limitations, Dynamic Memory Management Mechanism, use of new and delete operators, Methods for allocating and deallocating memory for single objects and array of objects, use of set_new_handler function to slide-25specify our own handler www.bookspar.com | Website for students | VTU NOTES

  2. Memory for Program variables get allocated and deallocated during the runtime only. Eg – we write int x; in some function of the code. When the code containing this line is compiled and linked, an executable file is generated. When executable file is executed, all instructions contained inside It, including ones to allocate memory for x are executed. Hence memory gets allocated for ‘x’ during runtime. This is known as Static Memory Allocation( although memory gets allocated during runtime only.) IntroductionStatic Memory Management www.bookspar.com | Website for students | VTU NOTES

  3. The compiler writes instructions in the executable to De-allocate the memory previously allocated for ‘x’ when it encounters the end of the function in which ‘x’ was declared in the source code. When the executable file is executed, all instructions inside it including the ones to deallocate memory for ‘x’ are executed. Hence the memory for ‘x’ gets deallocated during runtime. This is known as Static Memory Allocation Static Allocation and deallocation of memory has limitations: www.bookspar.com | Website for students | VTU NOTES

  4. It is rigid • The programmers are forced to predict the total amount of data the memory will utilize. • They write statements to declare precalculated amounts of Memory • During runtime, if more memory is required, static memory allocation cant fulfill the need. Static Allocation and deallocation of memory has limitations: www.bookspar.com | Website for students | VTU NOTES

  5. As in SM allocation and deallocation, in DM allocation and deallocation also, memory gets allocated and deallocated during Runtime. However the decisions to do so is taken dynamically in response to the requirements arising during runtime itself. If the program is running and user indicates the need to feed in more data, a memory block sufficient to hold additional amount of data is immediately allocated. For this code, using relevant functions and operators provided by C & C++ has to be explicitly written in source code. Dynamic Memory - Allocation supported in C and C++,overcomes the drawbacks of static memory Allocation. www.bookspar.com | Website for students | VTU NOTES

  6. Again, once a certain block of memory is no longer Needed, it can be returned to OS. For this again, code using the relevant functions and Operators provided by C & C++ has to be explicitly written in the source code www.bookspar.com | Website for students | VTU NOTES

  7. //dynamic.cpp //new operator, keyword takes a #include <iostream.h> // predefined datatype as operand( int) void main() //new allocates memory to hold 1 value of { int *iptr; //datatype i.e. passed as a parameter to it in iptr = new int; // heap( 4 bytes). Finally it returns the address *iptr=10; //of the allocated block. The allocated block cout << *iptr << endl; // can then be accessed through the } //pointer Dynamic Memory Allocation – is achieved in Cusing malloc(), calloc & realloc() functions. In C++,it is achieved through new operator. www.bookspar.com | Website for students | VTU NOTES

  8. Statement: int *iptr; 1265 iptr xxxx Four bytes get allocated for iptr containing junk value with adrresses from 1265 to 1268(say) Figure for Dynamic Memory Allocation www.bookspar.com | Website for students | VTU NOTES

  9. Statement: iptr = new int; 1265 5972 iptr The new operator allocates memory in the heap to hold 1 integer type value. Suppose block from byte with address 5972 to byte with address 5975 get allocated. The new operator returns the base address of block (5972). This value gets stored in iptr. 5972 xxxx 4 bytes www.bookspar.com | Website for students | VTU NOTES

  10. Statement : *iptr=10; 1265 5972 iptr fig - Dynamic Memory Allocation iptr is dereferenced and value 10 gets written into the memory Block of 4 bytes at which iptr points( 5972 to 5975). 5972 10 www.bookspar.com | Website for students | VTU NOTES

  11. Statement : cout << *iptr << endl; 1265 5972 iptr iptr is again dereferenced and value 10 gets written into the memory block of 4 bytes to which iptr points (5972 to 5975) is read. 5972 10 www.bookspar.com | Website for students | VTU NOTES

  12. The new operator can be used to create multiple blocks of memory also shown in dynarray.cpp General Syntax of new operator<pointer> = new <datatype>; www.bookspar.com | Website for students | VTU NOTES

  13. The Set_new_handler() function – New operator attempts to capture more chunks of memory from heap during run-time. If there is no memory available to satisfy this attempt, we get out of memory condition. new operator when faced with out-of-memory condition, calls a global function -> new_handler function, then throws an exception bad_alloc. We can specify our own new handler() function also. Set_new_handler() function www.bookspar.com | Website for students | VTU NOTES

  14. We can specify that the New operator upon encountering out-of-memory-condition, calls a function of our choice. This is done by calling ‘set_new_handler() fn and passing the name of function desired as a parameter to it. Prototype of set_new_handler is found in new.h header file. New_handler set_new_handler(new_handler); New_handler is a datatype and a function pointer Type. www.bookspar.com | Website for students | VTU NOTES

  15. The formal argument of the set_new_handler() function is a function pointer. If we pass name of our desired function as a parameter to set_new_handler() function, all subsequent out-of-memory conditions cause new operator to call it and our desired function becomes new_handler. When set_new_handler() is called , it returns a pointer to the previous new handler function Illustrative example new_handler.cpp Code for specifying a new_handler function www.bookspar.com | Website for students | VTU NOTES

  16. If os is unable to allocate the requested amount of memory, from given code, new operator fails. new_handler function is called. The call to set_new_handler() before the call to new operator , has already set function myNewHandler as new handler. Important Characteristic of new operator – When its request for memory fails, it calls new handler function repeatedly until the request is satisfied. We can make new_handler function log an error message and then call the abort() function. www.bookspar.com | Website for students | VTU NOTES

  17. Void myNewHandler() { //statement to log a suitable error message Abort(); } Another action – Replace the existing new handler by another one i.e. call the set_new_handler() from within the existing new handler and pass name of new handler as a parameter to it. Code for Defining a new handler function www.bookspar.com | Website for students | VTU NOTES

  18. #include <new.h> void main() { //make an attempt to resolve out of memory condition If (above_attempt_fails) set_new_handler(myAnotherNewhandler); } Best way to define new handler is to allocate some buffer in advance and free it part by part when the need arises. Such a call should be preceded by the code that attempts to resolve out-of-memory condition.The new handler should be replaced only if this attempt fails www.bookspar.com | Website for students | VTU NOTES

  19. A constructor gets called automatically for each object that has just got created. • Appears as member function of each class whether It is defined or not. • Has same name as that of the class and doesn’t return anything (not even void ) Constructor Prototype <class name> (<parameter list>); • Constructor fulfills the need to guarantee the data initialization. Constructors www.bookspar.com | Website for students | VTU NOTES

  20. Domain constraints on the values of data Members can also be implemented via constructors. Eg- We want value of all data member fInches of each object of class Distance to be between 0.0 and 12.0 at all times within the lifetime of object. But this condition get violated in case of an object just created. However introducing a suitable constructor to the class Distance can enforce this condition. The compiler emdeds a call to the constructor for each object when it is created. Suppose a class A has been declared as follows. www.bookspar.com | Website for students | VTU NOTES

  21. /*A.h*/ Class A { Int x; Public: void setx(const int = 0); int getx(); }; Suppose a class A is declared as follows www.bookspar.com | Website for students | VTU NOTES

  22. /*Amain.cpp*/ Void main() { A A1; //object declared … constructor called } Code for constructor getting called automatically for an object when it is created. Consider a statement that declares an object of class A as follows www.bookspar.com | Website for students | VTU NOTES

  23. Statement in main() is transformed into Following statements A A1; //memory allocated for object (4 bytes) A1.A //constructor called implicitly by compiler Second statement is transformed to A(&A1); -> C calls that object of class A passed as parameter for this pointer. C++compiler after ensuring that none of nonmfs are accessing private data of the class A, it converts C++ code to C code. www.bookspar.com | Website for students | VTU NOTES

  24. A *Aptr; Aptr = new A; // constrcutor called implicitly //by compiler The second statement is converted into a sequence of 2 statements Aptr = new A; Aptr -> A(); // constructor called implicitly by compiler. A(Aptr); //see chapter 2 Constructors don’t allocate memory for objects. They are mfs called for each object immediately after memory has been allocated for the object. Similarly, the constructor is called for each object i.e. created dynamically in the heap by compiler. www.bookspar.com | Website for students | VTU NOTES

  25. class String { //character pointer to point at the char *cStr; //character array long unsigned int len; // to hold length of //character array /*rest of the class string*/ }; Class CString with 2 private data members. www.bookspar.com | Website for students | VTU NOTES

  26. Suppose s1 is an object of class string and string abc has been assigned to it. This can be shown as below 27 101 101 3 cstr a b c \0 len s1 Fig- Memory layout of an object of class String www.bookspar.com | Website for students | VTU NOTES

  27. Constructors take arguments and can hence be overloaded by 1. Passing initial values for the data members for the data members contained in the object of a particular class Parameterized Constructors www.bookspar.com | Website for students | VTU NOTES

  28. Eg – The Distance class in a C++ program can also be overloaded by passing initial values for data Members iFeet & fInches as follows in class Distance and member function definition. /*distance.h*/ class Distance { public: Distance(); Distance(int, float); //prototype of parameterized //constructor /*rest of class Distance }; www.bookspar.com | Website for students | VTU NOTES

  29. /* beginning of distance.cpp*/ #include “Distance.h” Distance::Distance(){ iFeet = 0; fInches=0.0; } www.bookspar.com | Website for students | VTU NOTES

  30. Distance :: Distance( int p, float q) { iFeet = p; setInches(q); } /*definitions of the rest of the functiions of class Distance*/ www.bookspar.com | Website for students | VTU NOTES

  31. /*distTest1.cpp*/ #include <iostream.h> #include “Distance.h” void main() { Distance d1(1, 1.1); //parameterized constructor //called cout << “d1.getFeet() << “ “ << d1.getInches(); } Listing shows A user defined parameterized Constructor called by creating an object in the Stack O/P – 1 1.1 SLIDE-A www.bookspar.com | Website for students | VTU NOTES

  32. /*distTest2.cpp*/ #include <iostream.h> #include “Distance.h” void main() { Distance *dptr; dptr = new Distance(1, 1.1); //parameterized constructor //called cout << “dptr->getFeet() << “ “ << dptr->getInches(); } Listing shows A user defined parameterized constructor – called by creating an object in the heap. O/P 1 1.1 SLIDE-B www.bookspar.com | Website for students | VTU NOTES

  33. First line of main() in Slide-A and second line Of main() in slide-B show the syntax for passing values to the parameterized constructor Parameterized constructor is prototyped and defined like any other member function but it doesn’t return any value. www.bookspar.com | Website for students | VTU NOTES

  34. Then the following statement will not compile Distance d1; //Error no matching constructor The formal arguments of the parameterized constructor can be assigned default values as in other member functions. Here default constructor function should be provided, else an ambiguity error arise Note – If parameterized constructor is provided and zero argument constructor is not provided, compiler will not provide default constructor. www.bookspar.com | Website for students | VTU NOTES

  35. The formal arguments of the parameterized constructor can be assigned default values as in other member functions. Here default constructor function should be provided, else an ambiguity error arise when we attempt to create an object without passing any values to the constructor www.bookspar.com | Website for students | VTU NOTES

  36. class Distance { public: //Distance(); //zero argument constructor //commented out Distance(int = 0, float=0.0); //default values //given /*rest of the class Distance*/ Listing – Default values given to parameters of a parameterized constructor make zero argument constructor unnecessary www.bookspar.com | Website for students | VTU NOTES

  37. If we write , Distance d1; An ambiguity error arises if zero argument constructor is also defined. Reason – Both Parameterized and default constructor can resolve this statement. www.bookspar.com | Website for students | VTU NOTES

  38. Lets create a parameterized constructor for the class string and assign default value for the argument of the parameterized constructor. The constructor would handle the following statements. String s1(“abc”); or char *cPtr=“abc” String s1(cptr); or char Arr[10] = “abc”; String s1(cArr); In each of these statements, we are passing the base address of the memory block in which the string itself is stored to the constructor www.bookspar.com | Website for students | VTU NOTES

  39. Case - 1 string s1(“abc”); 1. Here base address of memory block of 4 bytes in which the string abc is stored is passed as a parameter to the constructor 2. But the constructor of the class String should be defined such that s1.cStr is made to point at base of a different memory block of 4 bytes in the heap area that is exclusively allocated for the purpose. 3. Only the contents of memory block, whose base address is passed to constructor, should be copied into memory block at which s1.cSptr points. Finally, s1.len should be set to 3. www.bookspar.com | Website for students | VTU NOTES

  40. p is a formal argument of the constructor. The address of the memory block containing the passed string is 50. This address 50 is passed to the constructor. Hence value of p = 50. But constructor should execute in such a manner that a different block i.e. long to hold the string at which p is pointing should also be allocated dynamically in heap area that extends from 101 to 104. The base address of this block of memory is stored in pointer embedded in s1. The string is copied from the memory block at which p points to memory block at which s1.cStr points. Finally s.len is appropriately set to 3. www.bookspar.com | Website for students | VTU NOTES

  41. 50 A b c \0 27 101 3 A b c \0 cStr len s1 The formal argument of the parameterized constructor for the class String will be a character pointer because address of a memory block containing a string has to be passed to it. Lets call this pointer p. After the statements String S1(“abc”); executes, the following scenario should emerge. 50 Assigning a string to an object of class String www.bookspar.com | Website for students | VTU NOTES

  42. The value of cPtr is passed as a parameter to the constructor. This value is stored in p. Hence p & cPtr points to the same place. s1.cStr should be made to point at a base address of a different memory block of 4 bytes that has been exclusively allocated for the purpose. Only the contents of memory block whose base address is passed to the constructor should be copied into memory block at which s1.cStr points. Case – 2 char *cPtr = “abc”;Strings1(cPtr); www.bookspar.com | Website for students | VTU NOTES

  43. 50 A b c \0 101 3 A b c \0 cPtr 50 50 27 p cStr 101 len Assigning a string to an object of class String www.bookspar.com | Website for students | VTU NOTES

  44. Fig - Assigning a string to an object of the class String Case-3char cArr[10] = “abc”;string s1[cArr] cArr 50 50 50 a b c \0 p 27 101 3 a b c \0 cStr 101 len s1 www.bookspar.com | Website for students | VTU NOTES

  45. is very similar to II case. Here we are passing the name of the array. But name of the array is itself is a fixed pointer that contains the address Of the memory block containing actual address of array i.e. seen in diagram. The formal argument of the constructor should be as follows : const char *const 1. It should be a constant pointer because throughout the execution of the constructor, it should continue to point to the same memory block. www.bookspar.com | Website for students | VTU NOTES

  46. It should be a pointer to a constant because even inadvertently, the library programmer should not dereference it to change the contents of the memory block at which it is pointing. • Specify a default value for ‘p’(NULL) so that there is no need to need to seperately define a zero default Constructor Definition of class String along with prototype of the constructor and its definition are as follows www.bookspar.com | Website for students | VTU NOTES

  47. Class String { char *cStr; long unsigned int len; public: //Default constructor*/ String(const char *const p = NULL); const char *getString(); /*rest of the class String*/ }; www.bookspar.com | Website for students | VTU NOTES

  48. String::String(const char* const p){ if (p==NULL) { cStr=NULL; len = 0; } else { len = strlen(p); // dynamically allocate a seperate cStr=new char[len+1]; //memory block & copy into it strcpy(cStr,p); } /*string.h*/#include “String.h”String::String(){ www.bookspar.com | Website for students | VTU NOTES

  49. Const char *string::getString() { return cStr; } /*string.cpp*/ void main() { String s1(“abc”); //pass a string to parameterized //constructor display the string Cout << s1.getString() << endl; } user-defined parameterized constructor for acquiring memory outside the object www.bookspar.com | Website for students | VTU NOTES

  50. Another function called getstring is written in class String that enables to display the string itself and returns a const char* so that only pointer to a constant can be equated to a call to this function const char* p = s1.getstring(); www.bookspar.com | Website for students | VTU NOTES

More Related