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.
Basis | free | delete |
---|---|---|
Refers to | A Library function | An operator |
Ideal for | Deallocating memory occupied using malloc,calloc and realloc function | Releasing memory which is allocated using new keyword |
Overriding | Not Possible | Possible |
Execution speed | slow | fast |
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)
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;
This post was last modified on September 23, 2022