CPP

Memory management operators

  • Arrays can be used to store multiple homogenous data but there are serious drawbacks of using arrays.
  • Programmer should allocate the memory of an array when they declare it but most of time, the exact memory needed cannot be determined until runtime.
  • The best thing to do in this situation is to declare the array with maximum possible memory required (declare array with maximum possible size expected) but this wastes memory.
  • So, To avoid wastage of memory, you can dynamically allocate the memory required during runtime using new and delete operator.
 

What are memory management operators?

There are two types of memory management operators in C++:
  • new
  • delete
These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways.
 

New operator:

  • The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any type.

General syntax of new operator in C++:

pointer variable = new datatype;
  • In the above statement, new is a keyword and the pointer variable is a variable of type datatype.
 

For example:

1. int *a = new int;
2. *a = 20;
      or
3.  int *a = new int(20);
  • In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point.
  • the pointer variable a holds the address of memory space allocated.
 

delete operator:

  • The delete operator in C++ is used for releasing memory space when the object is no longer needed. 
  • Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory.

General syntax of delete operator in C++:

delete pointer variable;

 

Example:

#include <iostream>
 
void main()
{
//Allocates using new operator memory space in memory for storing a integer datatype
int *a= new int;
*a=100;
cout << " The Output is:a= " << *a;
//Memory Released using delete operator
delete a; 
}

Output:

The Output is:a=100

In the above program, the statement:

int *a= new a;

Holds memory space in memory for storing a integer datatype.




Subscribe us on Youtube

Share This Page on

Questions


Atharv | 25-Jul-2018 12:45:47 am

What is memory management operator . Explain with an example.


Ansh | 27-Nov-2018 01:58:56 pm

What is meant by quantifier? Name the various quantifier used in c++.


Ask Question