new and delete allocate and release heap memory for single objects and arrays. They call constructors/destructors—unlike malloc/free in C.
Single object
int* p = new int(5);
delete p;
p = nullptr;
In modern C++, prefer std::make_unique and containers so cleanup is automatic.
Important interview questions and answers
- Q: new vs malloc?
A:newinvokes constructors and pairs withdelete;mallocis C-style raw bytes. - Q: double delete?
A: Undefined behavior—set pointer tonullptrafter delete or use smart pointers.
Self-check
- What calls the destructor for heap objects?
- Modern alternative to raw new/delete?
Pitfall: Every new needs matching delete (or array forms)—prefer std::make_unique so destructors run automatically.
Interview prep
- new vs malloc?
newinvokes constructors and pairs withdelete;mallocallocates raw bytes in C style.- Double delete?
Undefined behavior—use smart pointers or set pointer to nullptr after delete.