Dynamic Memory Allocation in C++

Dynamic memory allocation

On this page we will discuss about Dynamic Memory Allocation in C++ . Allocation of memory at run time based on the requirement of the user is called dynamic memory allocation.Dynamic memory allocation helps us to avoid wastage of storage and hence it is very important to understand it.

memory-card

Dynamic Memory Allocation in C++

  • 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

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;
}

Output:

*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 <<  "\n" <<  *(p + 0) << "\n";	//garbage value
   cout << *(p + 2) << "\n";	//garbage value
  
  return 0;
}

Output:

how many elements?:2

enter elelments:13 23

elements are:13	23	
1540455798
1585091451

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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription