Dynamic Memory Allocation in C++

New and Delete in C++

Dynamic memory allocation

  • Allocation of memory at run time based on the requirement of the user is called dynamic memory allocation
  • Dynamic memory allocation can be done using new operator in C++
  • In all the Dynamic Memory, allocation happens in Heap Area as heap can extend or shrink  at any time
memory-card

New operator

Using the new keyword, the required number of bytes of memory is allocated at run time. 

Syntax:

data_type *ptr=new datatype(value);

Example

int *p=new int(100);//4 bytes allocated

Delete operator

The memory allocated using new can be released and taken by at any time in between the program using delete keyword

Syntax:

delete ptr; // Release memory pointed by pointer-variable
Here, ptr is the pointer that points to the data object created by new. Example:
delete p;
To free the dynamically allocated array pointed by pointer-variable:
delete[] pointer-variable; //Release block of memory pointed by pointer-variable
Example:
delete[] p;// It will free the entire array pointed by p.

Example program to demonstrate new and delete

Run
/* program to demonstrate new and delete*/
#include<iostream>
using namespace std;
int main()
{
int *p;
float *q;
char *r;

p=new int(10);//allocates 2 bytes and the pass the address to p
q=new float(1.5);//allocates 4 bytes and the pass the address to q
r=new char('x');//allocates 1 bytes and the pass the address to r

cout<<"*p="<<*p<<" *q="<<*q<<" *r="<<*r<<endl;;
delete p;// release the memory allocated to p 
cout<<"*p="<<*p<<" *q="<<*q<<" *r="<<*r<<endl;;
return 0;
}

O/P

*p=10 *q=1.5 *r=x
*p=garbage value *q=1.5 *r=x
In the above program, 2 bytes are allocated and the value of 10 is stored and the address passed to ‘p’, similarly for ‘q’ and ‘r’. in the end, p is deleted i.e the memory is taken back, so ‘p’ no more points to that address .hence we get a garbage value if we access any memory after deleting it

Normal Array Declaration vs Using new

  • Normal arrays are deallocated by the compiler (If the array is local, then deallocated when the function returns or completes).
  • However, dynamically allocated arrays always remain there until either they are deallocated by programmer or program terminates.

Program to demonstrate array creation using new

Run
/* Program to demostrate array creation using new */
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"how many elements?:"; cin>>n;
int *p=new int[n];// creates n bytes in heap
cout<<"\nenter elelments:";
for(int i=0;i<n;i++) cin>>p[i];
cout<<"\nelements are:";
for(int i=0;i<n;i++)
cout<<*(p+i)<<"\t";
delete []p;//release the memory 
cout<<*(p+0)<<"\n";//garbage value
cout<<*(p+2)<<"\n";//garbage value
return 0;
}

What happens if enough memory is not available at runtime?

  • In rare cases required memory may be available at runtime In such case program may  terminate abnormally
  • To avoid this we can make use of an exception defined in std::bad_alloc, in which case it returns a NULL pointer and a user-defined message can be displayed to avoid confusion to the programmer
  • Therefore, it may be a good idea to check for the pointer variable whether the  required memory is available or not
int *p = new(nothrow) int;
if (!p)
{
cout << "Sorry:Memory not avaialble to allocate\n";
}

Need for dynamic memory allocation

Static Memory Allocation

  • Allocating memory at design time or compile time is known as Static memory allocation.
  • In Static memory allocation Memory once allocated neither extended or deleted,
  • Due to which there is a chance of wastage or shortage of memory
  • Non-static and local variables get memory allocated on Stack Area
Example:
int a[5];//allocates 5xsize(int)=10bytes
int c[5]={1,2,3};//4 bytes wasted as space for 2 elements is unused
int b[2]={1,2,3};//need 4 bytes more
  • Static memory once allocated cant be deleted by the programmer in between, it is deleted only by the compiler at the end
  • In large Programs in real time projects after usage giving the memory back and having free space would enhance the performance