1
Dynamic Memory (new / delete)
C++
new allocates memory on the heap at run time; delete frees it. Forgetting delete causes a memory leak.
Local variables live on the stack, new allocates on the heap
int *p = new int(5); // single int on heap
delete p;
int n = 5;
int *arr = new int[n]; // array on heap
delete[] arr; // use delete[] for arrays
// Modern C++: smart pointers free memory automatically
unique_ptr<int> u = make_unique<int>(10); // needs <memory>
Q & A
- malloc vs new?
malloc is a C function that returns void* and does not call constructors. new is a C++ operator, returns the correct type and calls the constructor; delete calls the destructor.