Core Module
12 min forge

C++ Dynamic Memory

Mastering heap allocation with new and delete.

C++ Dynamic Memory

πŸ“˜ What is it

Dynamic memory allocation allows you to allocate memory at runtime on the Heap. Unlike stack memory, heap memory must be manually managed by the programmer using new and delete.

⚑ When to use

Use dynamic memory when the amount of data is not known at compile-time, or when you need data to persist beyond the scope of a single function.

🧠 Time complexity

  • Allocation (new): $O(1)$ average (depends on allocator).
  • Deallocation (delete): $O(1)$.

πŸ’» Code example

cpp Standard
// Single variable int *ptr = new int(5); delete ptr; // Array on heap int *arr = new int[10]; delete[] arr; // Use delete[] for arrays!

❌ Common mistakes

  • Memory Leaks: Forgetting to call delete.
  • Double Free: Calling delete on the same pointer twice (causes crash).
  • Using delete instead of delete[] for arrays.
  • Accessing memory after it has been deleted.