Difference between delete and free() in C++ with an example

In this tutorial, you will be learning the difference between delete and free() in C++ with a simple example.

C++ provides two dynamic allocation operators: new and delete 
C++ supports dynamic allocation functions: free( ) and malloc( )

Difference between delete and free() in C++ with simple example

delete and new operator: The new operator allocates memory and returns a pointer. The delete operator free memory previously allocated using new. The general form is:

var=new type; //var is a pointer variable
delete var;

free() and malloc(): The malloc() function returns a pointer to the first byte of a region of memory of size s that has been allocated from the heap, if fail returns null. The free() function returns the memory pointed by a pointer p to the heap. This makes the memory available for future allocation.

#include<cstdlib>
void *malloc(size s);
void free(void *p);

Example:

Here is a program that allocates memory to hold an integer:

#include<stdio.h>
#include<cstdlib>
#include<iostream>
using namespace std;

int main()
{
  int *p;
  int *p1;
  try
  {
    p=new int(87); //initialize to 87
    
  }
  catch(bad_alloc e)
  {
    cout<<"Allocation failed!";
    return 1;
  }
  p1=(int*) malloc(sizeof(int));
  *p1=100;
  cout<<"At "<<p<<" is the value "<<*p<<"\n";
  cout<<"At "<<p1<<" is the value "<<*p1<<"\n";
  delete p; 
  free(p1);
  
  return 0;
  
}

Output:

At 0x3618d0 is the value of 87
At 0x4567d0 is the value of 100

The program assigns to p and p1 an address in the heap that is large enough to hold integers. The delete operator must be used only with valid pointer previously allocated by using new. The free() function frees the allocated memory for p1.

Main difference:

  1. delete is a dynamic allocation operator whereas free() is a dynamic allocation function.
  2. delete is used to free the allocated memory using new whereas free() is used to deallocate the memory allocated by malloc().
  3. delete is faster than free().

Hope, you have understood the difference between delete and free(). Feel free to comment.

Also read,

Program to calculate the percentile of an array in C++

Leave a Reply

Your email address will not be published. Required fields are marked *