C++ Dynamic Memory
`new` allocates memory on the heap at runtime, returning a pointer, and `delete` frees it when you're done. Forgetting to `delete` causes a memory leak, and using memory after deleting it causes a dangling pointer bug.
Modern C++ strongly prefers smart pointers (`std::unique_ptr`, `std::shared_ptr` from `<memory>`) over raw new/delete, since they automatically free memory when no longer needed, preventing leaks.
new and delete
`int* p = new int(5);` allocates a single int on the heap; `delete p;` frees it. For arrays, use `new int[10]` and `delete[] arr` (note the brackets).
Smart pointers
`std::unique_ptr<int> p = std::make_unique<int>(5);` automatically deletes the memory when p goes out of scope โ no manual delete needed.
int* p = new int(42);
std::cout << *p;
delete p;42new allocates on the heap; delete frees it manually.
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(42);
std::cout << *p;42unique_ptr automatically frees the memory when it goes out of scope.
Key points
- new allocates heap memory; delete frees it.
- new[]/delete[] must be paired for arrays.
- Forgetting delete causes a memory leak.
- std::unique_ptr/shared_ptr automate cleanup safely.
