Articles

Difference Between Delete and free() in C++

Share

In this article, we’ll be discussing the meaning of the delete operator and free() function in C++ and the differences between them.

Both delete and free() are used for releasing the memory allocated at runtime. The main difference between them is, the delete operator deallocates memory for objects which are dynamically allocated through new keyword, whereas, the free() function deallocates memory that is dynamically allocated through malloc, calloc or realloc function.

Difference Between Delete and free() in C++

Basisfreedelete
Refers toA Library functionAn operator
Ideal forDeallocating memory occupied using malloc,calloc and realloc functionReleasing memory which is allocated using new keyword
OverridingNot PossiblePossible
Execution speedslowfast

free() function in C++ :

The main job of the free function is to release the memory which is allocated at the runtime. The free() function can be used in both C as well as C++ programming language.

It releases dynamically allocated memory created by calloc,realloc and calloc functions and provides extra reusable heap memory that can be used later. It takes pointer whose memory to be released as an argument.

void free(void *ptr)

delete operator in C++

The delete operator also has the same job like free function, that is, to release the memory which is allotted at the runtime. The delete operator is most commonly used in C++ programming.

It can defined as an operator which is used to release the memory allocated by new keyword such as objects and arrays. In C++, when delete is used with an object, it first calls the destructor of that particular object and then after deallocates the memory occupied by it. However, in the case of free(), no destructor is called of the respective object.

delete obj;

Key Differences between Delete and free() in C++

  1. The free function is basically a library function which resides in the stdlib.h header file, while delete, on the other hand, is an operator which is most commonly used in C++ programming.
  2. In the free() function, there is no call made to the destructor after the release of the runtime allocated memory. On the other hand, in case of delete operator, there is a call made to the destructor before the release of the allocated memory.
  3. In case of the free() function, as we all know that this is a function and thus it requires to get its declaration from the header file which makes it slower. In case of delete operator, as it is an operator and we all know that an operator is faster paced than a function.

 

This post was last modified on September 23, 2022

Sandeep Verma

Published by
Sandeep Verma
Tags: C delete and free in c++ delete operator Difference FREE AND DELETE free and delete in c++ free delete free delete c++ free function free vs delete