C++ Basics · Chapter 9

Memory in C++: Dynamic Memory
& Pointers

Understand how memory works in C++ programs. Learn the difference between stack and heap, master pointers and references, and avoid memory leaks and dangling pointers.

By Arj Updated July 2025 15 min read No prior experience needed
What you'll learn
  • How memory works in a C++ program
  • The difference between stack and heap memory
  • How to work with pointers and references
  • How to dynamically allocate and deallocate memory
  • How to avoid memory leaks and dangling pointers

1Stack vs heap memory

C++ uses two main types of memory: stack and heap. Understanding the difference is crucial for writing efficient and bug-free code.

Memory TypeManaged ByLifetimeUse Case
StackCompilerAutomatically freedLocal variables, function calls
HeapManually managedRemains until deletedDynamic allocation (new)
cpp
int x = 5;            // Stored on the stack
int* p = new int(10); // Allocated on the heap

x is destroyed when the function ends. p points to heap memory, which must be deleted manually.

2What is a pointer?

A pointer is a variable that stores the memory address of another variable. It is one of the most powerful features in C++.

Declaring a pointer:

cpp
int x = 42;
int* ptr = &x;
  • &x means "address of x"
  • *ptr means "value at the address stored in ptr"

Accessing values:

cpp
cout << "x = " << x << endl;
cout << "Address of x = " << &x << endl;
cout << "ptr points to = " << ptr << endl;
cout << "Value at ptr = " << *ptr << endl;
Sample outputx = 42 Address of x = 0x7ffd5a8f2b1c ptr points to = 0x7ffd5a8f2b1c Value at ptr = 42

3Changing values via pointers

Using a pointer, you can modify the value of the variable it points to.

cpp
int x = 5;
int* p = &x;
*p = 10; // Changes x to 10

cout << x << endl;
Output10

4What is a reference?

A reference is an alias for another variable. Once created, it cannot be changed to refer to something else.

Syntax:

cpp
int a = 5;
int& ref = a;
ref = 10; // Changes a to 10

Unlike pointers:

  • References must be initialized when declared
  • No need to dereference (*) or use address-of (&) once bound
  • References cannot be reassigned to refer to a different variable
When to use references vs pointers
Use references for function parameters when you want to modify the original and you know the value will always exist. Use pointers when you need to reassign or when the value might be null.

5Dynamic memory allocation

You can allocate memory at runtime using new and free it using delete.

Example: Single variable

cpp
int* p = new int;
*p = 25;
cout << *p << endl;
delete p; // Free memory
Output25

Example: Dynamic array

cpp
int* arr = new int[5]; // allocate array of size 5

for (int i = 0; i < 5; i++) {
    arr[i] = i * 2;
}

for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

delete[] arr; // Always use delete[] for arrays
Output0 2 4 6 8
Always match new with delete
Use delete for single variables allocated with new, and delete[] for arrays allocated with new[]. Mixing them causes undefined behavior.

6Memory leaks

A memory leak occurs when you allocate heap memory and forget to deallocate it. The memory remains allocated until the program ends, wasting resources.

cpp
int* leak = new int(100);
// no delete -> memory leak
Preventing memory leaks
Every new must be paired with a delete. In larger programs, consider using smart pointers (unique_ptr, shared_ptr) to manage memory automatically.

7Dangling pointers

A dangling pointer points to memory that has already been deallocated. Using it leads to undefined behavior.

cpp
int* p = new int(50);
delete p;
*p = 10; // undefined behavior – dangling pointer

How to prevent: After deleting a pointer, set it to nullptr.

cpp
delete p;
p = nullptr;

8nullptr in C++

Modern C++ uses nullptr (instead of NULL) to represent an empty or invalid pointer. It is type-safe and avoids ambiguity.

cpp
int* p = nullptr;
if (p == nullptr) {
    cout << "Pointer is null" << endl;
}
OutputPointer is null

9Summary table

ConceptDescription
Stack MemoryAutomatically managed, for local variables
Heap MemoryManually managed using new and delete
PointerStores memory address, can modify values indirectly
ReferenceAlias for a variable, simpler than pointer
Memory LeakForgetting to delete heap memory
Dangling PointerUsing a pointer after memory is deleted
nullptrSafer way to check if pointer is empty

10Common mistakes to avoid

1. Forgetting to delete dynamically allocated memory
This causes memory leaks. Always pair new with delete.
2. Using a pointer after delete
This creates a dangling pointer. Set the pointer to nullptr after deletion.
3. Confusing * in declaration vs dereference
int* p declares a pointer. *p = 10 dereferences it to assign a value. They are different operations.
4. Trying to rebind a reference
Once a reference is assigned to a variable, it cannot be changed to refer to another variable.

11Mini exercises

Try these yourself
  1. Declare an int variable and a pointer to it. Change the variable's value using the pointer.
  2. Dynamically allocate an array of 5 integers, store values, print them, and free the memory.
  3. Use a reference to swap two values (without using pointers).
  4. Create a function that allocates an array using new and returns the pointer.

Hint: For swapping with references, declare void swap(int &a, int &b) and use a temporary variable.

12Quiz yourself

Memory Management Quiz
Question 1 of 10
Coming up next
Recursion in C++
Learn about functions that call themselves – recursion – and how they solve problems like factorials, Fibonacci, and the Tower of Hanoi.
Continue to Chapter 10

Stop wrestling with confusion.

Join thousands of students mastering Computer Science without the academic jargon.

From syntax to systems. We break down the hardest ideas in computer science so you can actually build things.

© 2026 Painless Programming. Built for students.
Scroll to Top