New and Delete operators in C++

Photo by LUM3N on Unsplash

New and Delete operators in C++

DMA(Dynamic Memory Allocation):

In C++ programmers can manually perform memory modification on this memory allocation is done on the heap(heap is a memory that a programmer can access which won't be known until the program is running).

DMA means creating memory at run-time.

Advantages of DMA:-

  • Better use of memory with the help of memory modification programs are more optimized and operates faster because of better memory management.

  • It reduces the workload of the processor.

In C++ two keywords are used to allocate and deallocate memory namely new and delete.

Use of 'new' keyword/operator:-

  • new operator is used to allocate memory dynamically for a variable or object at runtime.

  • We can also use the new operator to initialize value or create a memory block.

  •     // Integer value initialized with value 24.
        int *v = new int(24);
    
        // Create an array of size 10.
        int *p = new int[10];
    
  • Syntax of 'new' operator:

      pointer-variable = new data-type;
    

Code using 'new' operator:-

#include <iostream>

using namespace std;

int main() {

int *pointer;

pointer = new int(90); // using new keyword and initializing the value

cout<<*pointer;

return 0;

}

Use of 'delete' keyword/operator:-

The main function of the 'delete' keyword is to deallocate or free the memory allocated by new keyword it is important to free the memory because if not done can cause memory leak. Also, memory is available for further use of DMA.

Syntax of 'delete' operator:

// Release memory pointed by pointer-variable
delete pointer-variable;

Code using 'delete' operator:-

#include <iostream>

using namespace std;

int main() {

int *pointer;

pointer = new int(90); // using new keyword and initializing the value

cout<<*pointer;

delete pointer; // deleting the allocated memory block

return 0;

}

To delete an entire array of pointers:

delete[] p; // where p is array of pointer

Some useful examples related to the topic: examples(repl)