What is the difference between new and malloc in C++?

Pointnew / deletemalloc / free
LanguageC++C (also usable in C++)
ConstructorCalledNot called
Return typeThe correct pointer typevoid* (needs a cast)
On failureThrows std::bad_allocReturns NULL
SizeCalculated by the compilerYou give the bytes
#include <iostream>

struct Item {
    Item() { std::cout << "constructed\n"; }
    ~Item() { std::cout << "destroyed\n"; }
};

int main() {
    Item* p = new Item;       // allocates and constructs
    delete p;                 // destroys and frees
}
Output

constructed
destroyed

In modern C++ do not write them by hand. Use std::make_unique and containers. See Dynamic Memory and Smart Pointers.


Learn more about the similar topics:
Tutorials
C++ References and const References
C++ Pointers
C++ Dynamic Memory: new, delete and Smart Pointers
Exercises & Assignments
Swap two numbers using a reference function
Manage a resource with unique_ptr
Interview Questions & Answers
What is the difference between a reference and a pointer in C++?
What is the difference between new and malloc in C++?
What is a memory leak in C++ and how to avoid it?
What is nullptr in C++? What is the difference from NULL?
What is RAII in C++?
What is the difference between unique_ptr, shared_ptr and weak_ptr?
What is const correctness in C++?