Delete and free() in C++ Program


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().

Example

#include<stdio.h>
#include<stdlib.h>
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;
   getchar();
   return 0;
}

Updated on: 23-Mar-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements