Junior — Middle
What are the differences between the free() and delete() operators in C++?
sobes.tech AI
Answer from AI
Main differences between free() and delete() operators in C++:
-
free()is a function from the C language that releases memory allocated withmalloc(),calloc(), orrealloc(). It simply frees the memory block without calling object destructors. -
deleteis a C++ operator that frees memory allocated withnewand calls the destructor of the object, which is important for proper resource cleanup.
Example:
class MyClass {
public:
~MyClass() { std::cout << "Destructor called" << std::endl; }
};
// Correct:
MyClass* obj = new MyClass();
delete obj; // calls destructor and frees memory
// Incorrect:
MyClass* obj2 = (MyClass*)malloc(sizeof(MyClass));
free(obj2); // destructor will not be called, potential resource leaks
Using free() for C++ objects is dangerous because destructors are not called, which can lead to resource leaks. Similarly, delete should not be used on memory allocated with malloc(). Always match the allocation and deallocation methods.