0
0
CppComparisonBeginner · 4 min read

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++.

Aspectdeletefree
LanguageC++C (usable in C++)
Memory Allocation Pairnewmalloc
Calls DestructorYesNo
Syntaxdelete pointer;free(pointer);
Type SafetyYes (requires pointer to object)No (void pointer)
Usage ContextC++ objectsRaw 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++.

cpp
#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;
}
Output
Constructor called Destructor called
↔️

free Equivalent

This example shows how to allocate and free raw memory using malloc and free in C++.

cpp
#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;
}
Output
Array values: 10 20 30
🎯

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.
Mixing delete with malloc or free with new causes undefined behavior.
Use delete for C++ objects and free for C-style memory management.
Proper pairing of allocation and deallocation functions is essential for safe memory management.