• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Dynamic memory allocation in c++
 

Dynamic memory allocation in c++

on

  • 2,510 views

 

Statistics

Views

Total Views
2,510
Views on SlideShare
2,510
Embed Views
0

Actions

Likes
1
Downloads
78
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Dynamic memory allocation in c++ Dynamic memory allocation in c++ Presentation Transcript

    • 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.
    • 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.
    •  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.
    • 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.
    •  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};
    •  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.
    • 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.
    • 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.
    • 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
    •  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
    • 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(); }
    • OUTPUT: Constructor called a=5 Destructor called
    • 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(); }
    • OUTPUT: a=56378 // Garbage value // Didn’t call neither the constructor nor the destructor
    • 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.