Memory can be allocated on both stack and heap depending on one’s necessity. When a function is called, all the variables in the function gets allocated some memory contiguously, and when the function returns, these variables get deallocated automatically by the compiler. This kind of memory allocation is stack based.
Heap allocation is when you explicitly reserve some piece of memory through new/malloc/calloc/realloc. It is not contiguous, and it is our responsibility to release these chunks of memory that we previously allocated. free() and delete() are two operations that does this.They are memory deallocation functions having the same purpose. Yet they’re different, and without knowing the difference between the two, it is easier to get tempted to misplace these and create memory leaks.
Let’s start with what free does, and what delete does.
void free (void* ptr);
free() deallocates a memory block pointed to by ptr when the ptr was previously allocated memory via malloc or calloc or realloc. It is part of the C-standard library.
void operator delete[] (void* ptr) throw();
delete also deallocates the memory pointed to by ptr.
#include <bits/stdc++.h>
class Flower {
public:
Flower() {
std::cout << "In the Flower constructor\n";
}
~Flower() {
std::cout << "In the Flower destructor\n";
}
};
int main() {
Flower *rose = new Flower; // calls the constructor
delete(rose); // calls the destructor
std::cout << "Rose object cleared through a delete call\n";
Flower *jasmine = (Flower*)malloc(sizeof(Flower)); // doesn't make a call to the constructor, only assigns memory
free(jasmine); // doesn't call destructor
std::cout << "Memory assigned to jasmine object freed\n";
return 0;
}
Output
In the Flower constructor
In the Flower destructor
Rose object cleared through a delete call
Memory assigned to jasmine object freed
Few differences:
- free is used when memory is allocated using malloc or calloc or realloc. delete is used when it is allocated by calling new(). Undefined exceptions can occur if you allocate memory through malloc then use delete to release it and similarly, with new and free.
- free is a function whereas delete is an operator. One added advantage here is that delete[] can be overloaded with objects or can also be re-defined.
- delete calls the destructor whereas free doesn’t. So, in order to completely deinitialize the objects and release the memory, delete[] helps by implicitly calling the destructors, whereas free doesn’t make any call to the destructor.
- free is part of the C standard library, delete[] is C++ specific.
- delete[] can be overloaded to suit the object’s needs, but free can’t as it is a function imported from C-Standard library.