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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.