What is the difference between malloc/free and new/delete?
Short answer
malloc/free are C library functions that only allocate/free raw memory and don't call constructors or destructors; new/delete are C++ operators that also construct and destruct objects and are type-safe (no cast needed).
Advertisement
AModel answer
malloc/free are C library functions that only allocate/free raw memory and don't call constructors or destructors; new/delete are C++ operators that also construct and destruct objects and are type-safe (no cast needed). In C++ you should use new/delete (or better, smart pointers), not malloc, for objects with non-trivial lifetimes.
MyClass* a = (MyClass*)malloc(sizeof(MyClass)); // no ctor called
MyClass* b = new MyClass(); // ctor calledReal-world example
Mixing malloc with a C++ class skips its constructor, leaving members uninitialized and crashing later.
Likely follow-ups
- Why is new type-safe? | Can you mix malloc with delete?
Related topics