What is the difference between new and malloc in C++?
new is a C++ operator that allocates memory and calls the object's constructor, returns a correctly typed pointer, and is paired with delete. malloc is a C function that only allocates raw memory, does not call constructors, returns a void pointer you must cast, and is paired with free. In C++ you should prefer new, or better still smart pointers.
- new is a C++ operator that allocates memory and calls the constructor, paired with delete.
- malloc is a C function that allocates raw memory without calling constructors, paired with free.
- In modern C++ you rarely use either directly, preferring smart pointers.
Key differences
- Constructor: new calls it, malloc does not.
- Type: new returns the right type, malloc returns void* needing a cast.
- Sizing: new computes the size, malloc needs sizeof by hand.
- Release: new pairs with delete, malloc pairs with free.
int* a = new int(5); // allocates and initialises
delete a;
int* b = (int*)malloc(sizeof(int)); // raw memory, no init
free(b);
The modern answer is you rarely use either directly in good C++, because smart pointers like unique_ptr manage memory for you. Mentioning that shows you follow current best practice, not just the textbook difference.
Frequently asked questions
What happens if you mix new with free?
It causes undefined behaviour, because free does not call the destructor and the two allocators may manage memory differently. Always match new with delete.
What is the difference between delete and delete[]?
delete frees a single object, while delete[] frees an array and calls the destructor for every element. Using the wrong one is undefined behaviour.
Common follow up questions
Related interview questions
Want the full C++ guide?
Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the C++ guide All C++ questions