C++ ยท Chapter 47 of 49

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.

Example 1 (cpp)
int* p = new int(42);
std::cout << *p;
delete p;
Output
42

new allocates on the heap; delete frees it manually.

Example 2 (cpp)
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(42);
std::cout << *p;
Output
42

unique_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.
๐Ÿ’ก Note: Prefer smart pointers in new code; reach for raw new/delete only when you have a specific low-level reason.

๐Ÿ“ Quick Quiz

1. What frees memory allocated with new?

2. What is a consequence of forgetting delete?

3. Which smart pointer type automatically frees memory when out of scope?