Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Dynamic Memory (new / delete)

1 topic ยท 28 Nov 2026
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

Local variables live on the stack, new allocates on the heap

C++
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

  1. 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.