C++

Dynamic Memory Allocation in C++

Dynamic Memory Allocation allows a program to request memory from the operating system while it is running, rather than deciding exactly how much memory is needed at compile time. This is one of the most powerful features of C++, enabling the creation of flexible data structures like linked lists, trees, and resizable arrays.

1. The Theory: The Stack vs. The Heap

To understand dynamic memory, you must understand the two primary areas of memory used by your program:

A. The Stack (Static/Automatic Allocation)

  • Behavior: Managed automatically by the compiler. When a function is called, its variables are "pushed" onto the stack; when it returns, they are "popped" off.

  • Limitation: The size must be known at compile time. You cannot declare int arr[n]; if n is a variable chosen by the user (in standard C++).

  • Risk: The stack is relatively small. Large arrays can cause a Stack Overflow.

B. The Heap (Dynamic Allocation)

  • Behavior: A large pool of memory available to the program. The programmer manually requests space and must manually release it.

  • Benefit: Memory allocated here stays alive until you explicitly delete it, even if the function that created it ends.

  • Requirement: You access heap memory exclusively through Pointers.

2. The new and delete Operators

In C++, dynamic memory is managed using two specific keywords:

A. The new Operator

The new operator requests memory from the heap. If successful, it returns the address of that memory.

  • int* ptr = new int; // Allocates space for one integer.

  • int* arr = new int[10]; // Allocates space for an array of 10 integers.

B. The delete Operator

Because the system does not automatically reclaim heap memory, you must return it yourself.

  • delete ptr; // Deallocates a single object.

  • delete[] arr; // Deallocates an array (the [] is vital for arrays).

3. Long Theory: The Lifecycle and Management

Theoretically, dynamic memory introduces a new responsibility: Ownership.

A. Memory Leaks

If you allocate memory using new and then change your pointer to point somewhere else without calling delete, the original memory becomes "orphaned." It is still marked as "in use" by the OS, but your program no longer has the address to find it. If this happens in a loop, your program will slowly consume all available RAM and eventually crash.

B. The Dangling Pointer

If you call delete ptr;, the memory is freed, but the variable ptr still holds the old address. If you try to access *ptr again, you are accessing "dead" memory. This is called a Dangling Pointer.

  • Best Practice: After deleting, set the pointer to nullptr.

C. Allocation Failure

In rare cases, if the system runs out of RAM, new will fail. Theoretically, C++ handles this by throwing an std::bad_alloc exception.

4. Practical Code Example: Dynamic Arrays

This program asks the user how many items they want to store and creates an array exactly that size.

#include <iostream>
using namespace std;

int main() {
    int size;
    cout << "Enter the number of elements needed: ";
    cin >> size;

    // 1. ALLOCATION
    // Creating an array on the HEAP
    int* dynamicArr = new int[size]; 

    cout << "Enter " << size << " numbers:" << endl;
    for (int i = 0; i < size; i++) {
        cin >> dynamicArr[i]; // Accessing like a normal array
    }

    cout << "The numbers are: ";
    for (int i = 0; i < size; i++) {
        cout << dynamicArr[i] << " ";
    }
    cout << endl;

    // 2. DEALLOCATION
    // Crucial: We must free the memory!
    delete[] dynamicArr; 
    
    // 3. CLEANUP
    dynamicArr = nullptr; // Avoid dangling pointer

    return 0;
}

5. Static vs. Dynamic

FeatureStatic (Stack)Dynamic (Heap)
KeywordNone (Automatic)new and delete
SizeMust be a constant.Can be a variable.
LifetimeLimited to the function/scope.Until delete is called.
AccessDirect variable name.Indirectly via pointers.
PerformanceVery fast.Slightly slower (OS overhead).
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now