Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 12 Beginner

Dynamic Memory Allocation in C++

Updated: May 17, 2026
5 min read

# CHAPTER 12

Dynamic Memory Allocation

1. Introduction

When you declare an array like int arr[10];, its size is fixed. What if you don't know how much data the user will enter until the program is running? You need Dynamic Memory Allocation. This allows your program to request memory from the operating system on the fly.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Differentiate between Stack and Heap memory.
  • Use the new operator to allocate memory.
  • Use the delete operator to free memory.
  • Prevent Memory Leaks.
  • Allocate dynamic arrays.

3. Stack vs. Heap Memory

  • The Stack: Automatically managed. When you write int x = 5; in a function, it goes on the Stack. When the function ends, x is automatically destroyed. The Stack is small and fast.
  • The Heap: Manually managed. It is a massive pool of RAM. Variables here stay alive until you explicitly destroy them. If you forget to destroy them, you cause a memory leak.

4. The new Operator

Use new to request memory on the Heap. It returns a pointer to the allocated memory.
cpp
123456789101112
#include <iostream>
using namespace std;

int main() {
    // Request memory for one integer on the Heap
    int* ptr = new int; 

    *ptr = 42; // Store 42 in that memory location
    cout << "Value: " << *ptr << endl;

    return 0;
} // WAIT! WE HAVE A PROBLEM HERE!

5. The delete Operator (Preventing Leaks)

In the code above, when main() ends, the pointer ptr (on the Stack) is destroyed. But the integer 42 (on the Heap) is NOT destroyed! You have lost the address, and the memory is locked. This is a Memory Leak.

You must always use delete to free Heap memory.

cpp
123456
int* ptr = new int(42); // Allocate and initialize to 42

cout << *ptr << endl;

delete ptr;    // 1. Give the memory back to the OS
ptr = nullptr; // 2. Safety: prevent Dangling Pointer bugs

6. Dynamic Arrays

If a user wants to store N items, you can dynamically create an array of size N.
cpp
123456789101112131415161718192021
#include <iostream>
using namespace std;

int main() {
    int size;
    cout << "How many students? ";
    cin >> size;

    // Allocate an array dynamically based on user input!
    int* scores = new int[size]; 

    for(int i = 0; i < size; i++) {
        scores[i] = 100; // Initialize all to 100
    }

    // Freeing a dynamic array REQUIRES brackets []
    delete[] scores;
    scores = nullptr;

    return 0;
}

7. Memory-Level Visualization

text
12345678
Stack                  Heap
+-----------+          +-------------------+
| ptr       | -------> | 42 (Integer)      |
| (Address) |          | (Address: 0x5A)   |
+-----------+          +-------------------+

After `delete ptr`: The Heap block is freed.
After `ptr = nullptr`: The Stack pointer no longer points to 0x5A.

8. Common Mistakes

  • Memory Leak: Using new without a matching delete. If this happens in a loop, your program will consume all your RAM and crash the computer.
  • Dangling Pointer: Accessing a pointer *after* calling delete on it.
  • Wrong Delete: Using delete ptr; instead of delete[] ptr; on a dynamic array. This only deletes the first element of the array!
  • Double Free: Calling delete on the same pointer twice crashes the program.

9. Best Practices

  • Every time you type new, immediately type delete a few lines down so you don't forget.
  • Modern C++ (C++11) strongly recommends Smart Pointers (std::unique_ptr) instead of raw new/delete because they delete themselves automatically (covered in Chapter 25).

10. Exercises

  1. 1. Write a program that asks the user for a number, dynamically allocates a float, assigns the number to it, prints it, and deletes it.
  1. 2. Intentionally create a memory leak in a while(true) loop (WARNING: Open Task Manager to kill the process quickly!).

11. MCQ Quiz with Answers

Question 1

Which operator is used to allocate dynamic memory?

Question 2

Which operator frees dynamic memory?

Question 3

Memory allocated with new is stored where?

Question 4

What is a Memory Leak?

Question 5

How do you correctly delete a dynamic array int* arr = new int[10];?

Question 6

What happens to local variables when a function ends?

Question 7

Why should you set a pointer to nullptr after deleting it?

Q8. Can the size of a dynamic array be determined by user input at runtime? a) Yes b) No Answer: a) Yes
Question 9

What happens if you call delete on the same pointer twice (Double Free)?

Question 10

What does new return?

12. Interview Questions

  • Q: Explain the difference between Stack and Heap memory.
  • Q: In C++, what is the difference between malloc() (from C) and new? (Answer: new calls the constructor of an object, malloc does not).
  • Q: How do you track down a memory leak in a large C++ application? (Answer: Tools like Valgrind).

13. Summary

Dynamic memory allocation allows your program to adapt to data sizes at runtime by requesting Heap memory using new. However, with great power comes great responsibility: you MUST return that memory to the OS using delete to prevent memory leaks and dangling pointers.

14. Next Chapter Recommendation

In Chapter 13: Structures and Enumerations, we will learn how to group different data types together to create custom, complex data types like a Student or an Enemy.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·