Delete and free() in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand delete() and free() functions in C++.

Both of these functions are primarily used for the same purpose i.e freeing up unused memory. The delete() operator is for the ones allocated using new() and free() for the ones allocated using malloc().


int main(){
   int x;
   int *ptr1 = &x;
   int *ptr2 = (int *)malloc(sizeof(int));
   int *ptr3 = new int;
   int *ptr4 = NULL;
   //incorrect usage of delete
   delete ptr1;
   delete ptr2;
   //correct usage of delete
   delete ptr3;
   delete ptr4;
   return 0;
Published on 23-Mar-2020 12:53:28