Lesson 12 — Memory Management

Pointers

A pointer is a variable that stores a memory address rather than a value directly. Pointers are one of C++'s most powerful — and most misunderstood — features.

Declaring and Dereferencing Pointers

The & operator returns the memory address of a variable. A pointer variable, declared with *, stores that address. To access the value stored at the address a pointer holds, you dereference it, also with *.

C++ — Pointer basics
int age = 30;
int* agePtr = &age;   // agePtr stores the address of age

std::cout << "Value: " << age << std::endl;
std::cout << "Address: " << agePtr << std::endl;
std::cout << "Dereferenced: " << *agePtr << std::endl;

*agePtr = 31; // changes age through the pointer
std::cout << "New value: " << age << std::endl;

Null Pointers and Dynamic Memory

A pointer that isn't pointing to anything valid should be set to nullptr rather than left uninitialised. Pointers are also how C++ manages dynamically allocated memory with new and delete, though modern C++ favours smart pointers (from <memory>) to manage this automatically.

C++ — Dynamic allocation
int* dynamicNum = new int(42);
std::cout << *dynamicNum << std::endl;
delete dynamicNum; // free the memory when done
dynamicNum = nullptr;

Common Mistakes

  • Dereferencing a pointer that hasn't been initialised or has already been deleted — this leads to undefined behaviour.
  • Forgetting to delete memory allocated with new, causing a memory leak.
  • Confusing & (address-of) with * (dereference) — they are opposite operations.
  • Using a pointer after calling delete on it (a "dangling pointer") without setting it to nullptr.

Professional Tip

In modern C++, prefer std::unique_ptr and std::shared_ptr (from <memory>) over raw new/delete. They automatically free memory when it's no longer needed, eliminating most memory leaks and dangling pointer bugs.

Your Turn

Write a function void increment(int* n) that increases the value pointed to by n by 1. Call it from main() on a variable and print the result to confirm it changed.

Mini Quiz

What does the * operator do when placed before an already-declared pointer variable, such as *agePtr?