Describe new operator and delete operator

Describe new operator and delete operator.

- new and delete operators are provided by C++ for runtime memory management. They are used for dynamic allocation and freeing of memory while a program is running.
- The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.
- The general form of using them is :
p_var = new type;
delete p_var;
- new allocates memory on the heap. If there is insufficient memory, then new will fail and a bad_alloc exception will be generated. The program should handle this exception.
- Consider the following program :
#include <iostream>
#include <new>
using namespace std;
int main()
{
   int *p;
   try
   {
       p = new int; //dynamic allocation of memory
   }
   catch (bad_alloc x)
   {
       cout << “Memory allocation failed”;
   return 1;
   }
   *p = 100;
   cout <<”P has value”<<*p;
   delete p;   //free the dynamically allocated memory
   return 0;
}

What is new and delete operator?

- In C++, when you want dynamic memory, you can use operator new. It returns a pointer to the beginning of the new block of memory allocated. It returns a pointer to the beginning of the new block of memory allocated.
- When memory allocated by new operator is no longer required, it is freed using operator delete.
Distinguish between new and malloc and delete and free().
Distinguish between new and malloc and delete and free() - Delete is assocated with new and free(0 is associated with malloc()....
What is the difference between realloc() and free()? - C++
Difference between realloc() and free() - An existing block of memory which was allocated by malloc() subroutine, will be freed by free() subroutine.....
What is function overloading and operator overloading? - C++
What is function overloading and operator overloading? - C++ provides ability to overload most operators so that they perform special operations relative to classes.....
Post your comment