Dynamic memory allocation in c++


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Dynamic memory allocation in c++

  1. 1. PROBLEMS WITH NORMAL ARRAY VARIABLE DECLARATIONInt main() // 1 . Size fixed{ 1020 1022 1024 1026 1028Int A[5]; A[0] A[1] A[2] A[3] A[4]Int B[n]; // 2. Error..Size must be known at compile time.}Will not work for larger programs because of the limited size of thestack.
  2. 2. HEAP AND STACK Our program when loaded in to main memory is divided in to 4 segments : CODE,DATA,STACK,HEAP A data segment contains the global variables and static variables. A code(text) segment contains the executable instructions. A Stack segment store all the auto variables. Also each function call involves passing arguments from the caller to the callee. The callee may also declare variables. Function parameters ,return address and automatic local variables are accommodated in the stack. Hence a stack is an area of memory for storing data temporarily.
  3. 3.  Allocation and de allocation of memory in this area is done automatically . Heap segment is for dynamic memory management. It is for the programmers to manage. We can allocate memory when you feel the need for it and delete when you feel that the memory is no longer needed And it is the responsibility of the programmer to delete memory when no longer needed. Hence for array we can dynamically allocate memory of size which can be determined at run time. C programs use a pair of functions named malloc and free to allocate space from the heap. In C++ we use new and delete.
  4. 4. DEFINING A DYNAMIC ARRAY When we define an array variable, we specify a type , a name, and a dimension. int a[2] When we dynamically allocate an array, we specify the type and size but no name This new expression allocates an array of ten integers and returns a pointer to the first element in that array, which we use to initialize ptr. int *ptr = new int[10]; // array of 10 uninitialized integers (contain garbage value) Objects allocated on the free store are unnamed. We use objects on the heap only indirectly through their address.
  5. 5.  To value initialise the array we can use empty parentheses in the expression. int *pia2 = new int[10] (); // initialized to 0 This effectively send a request to the compiler to value-initialize the array, which in this case sets its elements to 0. The elements of a dynamically allocated array can be initialized only to the default value of the element type. The elements cannot be initialized to separate values as can be done for elements of an array variable. int a[2]={1,2};
  6. 6.  int* nums2 = new int[x]; // ok Value of x is obtained during run time and even the memory allocation is done dynamically For multidimensional arrays int x = 3, y = 4; int* nums3 = new int[x][4][5]; // ok int* nums4 = new int[x][y][5]; // BAD! Only the first dimension can be a variable. The rest must be constants.
  7. 7. DEALLOCATING MEMORY When we allocate memory, we must eventually free it. Otherwise, memory is gradually used up and may be exhausted We do so by applying the delete [] expression to a pointer that addresses the array we want to release: delete [ ] ptr; //de allocates the array pointed to by ptr The empty bracket pair between the delete keyword and the pointer is necessary It indicates to the compiler that the pointer addresses an array of elements It is essential to remember the bracket-pair when deleting pointers to arrays. For every call to new, there must be exactly one call to delete.
  8. 8. MALLOC AND FREE Memory allocation can be done using malloc as: int* nums = (int*)malloc(5*sizeof(int)); This is similar to int *nums = new int[5]; De allocation can be done using free as free(nums) This is similar to delete[ ] nums. C++ also supports malloc and free as we know that C++ is a superset of C.
  9. 9. WHY NEW IF MALLOC ? With simple variables and arrays new and delete does the same functionality as malloc and free respectively. But the scenario changes when we need to work with the classes where we use constructors to assign values to the data members. As with classes new allocates space to hold the object which are the instance of the class. new calls the object’s default constructor. Example : for a given class ‘cls’ , cls *ptr = new cls; // calls default constructor of cls. If not found , automatically compiler generated constructor is called
  10. 10.  cls *ptr = new cls(2); // calls one parameterized constructor of cls. If not found , throws error new returns a pointer to the object of the class. Though malloc does allocate memory for the given type it cannot call the constructor which are the special member functions that are used to assign values to variables. new is an operator, while malloc() is a function. new returns exact data type, while malloc() returns void pointer
  11. 11. EXAMPLE:#include<iostream> void disp()Using namespace std; { cout<<"na:"<<a; }class cls { }; int a; void main() public: { cls() { clrscr(); a=5; cls *ptr = new cls; cout<<"nConstructor called"; } ptr->disp();~cls() delete ptr;{ cout<<"nDestructor called"; } getch(); }
  12. 12. OUTPUT: Constructor called a=5 Destructor called
  13. 13. EXAMPLE:#include<iostream> void disp()Using namespace std; { cout<<"na:"<<a; }class cls { }; int a; void main() public: { cls() { clrscr(); a=5; cls *ptr = (cls*)malloc(sizeof(cls)) cout<<"nConstructor called"; } ptr->disp();~cls() free(ptr);{ cout<<"nDestructor called"; } getch(); }
  14. 14. OUTPUT: a=56378 // Garbage value // Didn’t call neither the constructor nor the destructor
  15. 15. CAUTION: MANAGING DYNAMIC MEMORY IS ERROR-PRONESome common program errors are associated with dynamicmemory allocation: Failing to delete a pointer to dynamically allocated memory, thus preventing the memory from being returned to the free store. Failure to delete dynamically allocated memory is spoken of as a "memory leak.” Applying a delete expression to the same memory location twice. This error can happen when two pointers address the same dynamically allocated object. If delete is applied to one of the pointers, then the objects memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.