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
deleteon the same pointer twice (causes crash). - Using
deleteinstead ofdelete[]for arrays. - Accessing memory after it has been deleted.