Delete vs free in C++: Key Differences and When to Use Each
delete is used in C++ to free memory allocated with new and calls the object's destructor, while free is a C function that releases memory allocated with malloc but does not call destructors. Use delete for C++ objects and free for C-style memory blocks.Quick Comparison
This table summarizes the main differences between delete and free in C++.
| Aspect | delete | free |
|---|---|---|
| Language | C++ | C (usable in C++) |
| Memory Allocation Pair | new | malloc |
| Calls Destructor | Yes | No |
| Syntax | delete pointer; | free(pointer); |
| Type Safety | Yes (requires pointer to object) | No (void pointer) |
| Usage Context | C++ objects | Raw memory blocks |
Key Differences
delete is designed for C++ objects allocated with new. It not only frees the memory but also calls the destructor of the object, allowing proper cleanup of resources like file handles or dynamic members.
On the other hand, free is a C library function that releases memory allocated by malloc, calloc, or realloc. It simply returns the memory to the system without calling any destructors, so it should not be used on C++ objects.
Using free on memory allocated with new or using delete on memory allocated with malloc leads to undefined behavior and can cause crashes or memory corruption.
Code Comparison
Here is how you allocate and deallocate memory for an object using new and delete in C++.
#include <cstdio> class MyClass { public: MyClass() { printf("Constructor called\n"); } ~MyClass() { printf("Destructor called\n"); } }; int main() { MyClass* obj = new MyClass(); delete obj; return 0; }
free Equivalent
This example shows how to allocate and free raw memory using malloc and free in C++.
#include <cstdlib> #include <cstdio> int main() { int* arr = (int*)malloc(3 * sizeof(int)); if (arr == nullptr) return 1; arr[0] = 10; arr[1] = 20; arr[2] = 30; printf("Array values: %d %d %d\n", arr[0], arr[1], arr[2]); free(arr); return 0; }
When to Use Which
Choose delete when working with C++ objects created with new because it ensures destructors run and resources are cleaned properly.
Choose free when managing raw memory blocks allocated with malloc or related C functions, especially in legacy or C-style code.
Never mix them: do not use delete on memory from malloc, and do not use free on memory from new.
Key Takeaways
delete frees memory and calls destructors for C++ objects allocated with new.free releases raw memory allocated with malloc but does not call destructors.delete with malloc or free with new causes undefined behavior.delete for C++ objects and free for C-style memory management.