Unit 3: Memory Management, Pointers & ReferencesLesson #11 / 20

Lesson 11: Dynamic Memory Management with new, delete & Heap Allocation

NSNextSemLast Updated: 5 Aug, 2026

🧠 Heap Memory Allocation & Destructors

Memory in C++ is divided into two primary regions:

  • 📦 Stack: Automatic memory managed by the OS compiler for local function variables.
  • 🌐 Heap: Dynamic memory managed manually by the programmer during runtime using new and delete.

  • ⚠️ Dynamic Allocation Operators

  • 🟢 new: Allocates memory for a single object on Heap and returns pointer.
  • 🟢 new[]: Allocates a contiguous array on Heap.
  • 🔴 delete ptr;: Frees single object Heap memory.
  • 🔴 delete[] ptr;: Frees dynamic array Heap memory.

  • 💻 Code Example: Dynamic Heap Array

    C++ Source Code (main.cpp)
    #include <iostream>
    int main() {
    int size;
    std::cout << "Enter dynamic array capacity: ";
    std::cin >> size;
    // Allocate array on Heap at runtime
    int *heapArr = new int[size];
    for (int i = 0; i < size; ++i) {
    heapArr[i] = (i + 1) * 10;
    }
    std::cout << "Heap Array Elements: ";
    for (int i = 0; i < size; ++i) {
    std::cout << heapArr[i] << " ";
    }
    std::cout << std::endl;
    // FREED HEAP MEMORY TO PREVENT MEMORY LEAKS!
    delete[] heapArr;
    heapArr = nullptr; // Dangling pointer safety
    return 0;
    }
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    > ⊞ Windows Tip: Tools like Diagnostic Tools in VS 2026 monitor ⊞ Windows heap allocation graphs in real-time to catch memory leaks!

    Interactive Knowledge Check

    Test your understanding of Lesson #11 concepts

    What happens if memory allocated with 'new int[100]' is freed using 'delete ptr;' instead of 'delete[] ptr;'?