Home Uncategorized Write a program to illustrate scope resolution, new and delete Operators. (Dynamic...

Write a program to illustrate scope resolution, new and delete Operators. (Dynamic Memory Allocation)

SHARE

AIM: C++ program to illustrate dynamic allocation and deallocation of memory using new and delete.

Dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free.

The C++ programming language includes these functions for compatibility with C; however, the operators new and delete provide similar functionality and are recommended by that language’s authors.

Many different implementations of the actual memory allocation mechanism, used by malloc are available. Their performance varies in both execution time and required memory.
Example 1
Example 2

SOURCE CODE:

Example 1:

#include<iostream>
using namespace std;
int main()
{
   int *p=new int[3],k;
   for(k=0;k<3;k++)
   {
      cout<<“Enter a number: “;
      cin>>*p;
      p++;
   }
   p-=3;
   cout<<“\n Entered numbers with their address are:\n”;
   for(k=0;k<3;k++)
   {
      cout<<“\n”<<*p<<“\t”<<p;
      p++;
   }
   p-=3;
   delete p;
}

Output :

Enter a number: 96
Enter a number: 32
Enter a number: 58
Entered numbers with their address are:
96           0xedbc20
32           0xedbc24
58           0xedbc28

Example 2:

#include <iostream>
using namespace std;
int main ()
{
   int* p = NULL; // Pointer initialization to null
   p = new int; // Request memory for the variable using new operator
   if (!p)
      cout << “allocation of memory failed\n”;
   else
   {
      *p = 29; // Store value at allocated address
      cout << “Value of p: ” << *p << endl;
   }
   float *r = new float(75.25); // Request block of memory using new operator
   cout << “Value of r: ” << *r << endl;
   int n = 5;
   int *q = new int[n]; // Request block of memory of size n
   if (!q)
      cout << “allocation of memory failed\n”;
   else
   {
      for (int i = 0; i < n; i++)
      q[i] = i+1;
      cout << “Value and address store in block of memory: \n”;
      for (int i = 0; i < n; i++)
         cout << q[i] << “\t”<<&q[i] << endl;
   }
   delete p;
   delete r; // freed the allocated memory
   delete[] q; // freed the block of allocated memory
   return 0;
}

Output:

Value of p: 29
Value of r: 75.25
Value and address store in block of memory:
1              0x22f6c60
2              0x22f6c64
3              0x22f6c68
4              0x22f6c6c
5              0x22f6c70

Note: The address is changed every, time when run the program. Here we observe that address value increment block by block.

Back to Programs.