Explain Memory Management in detail in c++?

Memory management is a process of managing computer memory6 and assigning the memory space to the programs to improve the overall system performance. Sometimes, exact memory is not determined until runtime. To avoid such a situation, we declare an array with a maximum size, but some memory will be unused. To avoid the wastage of memory, we use the new operator to allocate the memory dynamically at the run time.

A new operator is used to create the object.

A delete operator is used to delete the object.


int main()  
int size;  // variable declaration  
int *arr = new int[size];   // creating an array   
cout<<"Enter the size of the array: ";     
std::cin >> size;    //   
cout<<"\nEnter the element : ";  
for(int i=0;i<size;i++)   // for loop  
cout<<"\nThe elements that you have entered are :";  
for(int i=0;i<size;i++)    // for loop  
delete arr;  // deleting an existing array.  
return 0;

Malloc() vs new

The new operator constructs an object, i.e., it calls the constructor to initialize an object while malloc() function does not call the constructor. The new operator invokes the constructor.
The new is an operator, while malloc() is a predefined function in the stdlib header file.
In the new operator, we need to specify the number of objects to be allocated while in the malloc() function, we need to specify the number of bytes to be allocated.
For the new operator, we have to use the delete operator to deallocate the memory. For malloc() function, we need the free() function.

Delete() vs free

The delete is an operator that de-allocates the memory dynamically while the free() is a function that destroys the memory at the runtime.
When the delete operator destroys the allocated memory, then it calls the destructor of the class in C++, whereas the free() function does not call the destructor; it only frees the memory from the heap.
The delete() operator is faster than the free() function.