C++ · Advanced level

Advanced level · Module 2: Modern Memory Management · Lesson 1 of 4

Stack, Heap and Manual Memory

See where objects live, why manual new and delete are error-prone, and what goes wrong in practice.

In this lesson you will

  • Distinguish stack and heap allocation
  • Identify leaks, double deletes and dangling pointers

Key concepts

stack allocationheap allocationmemory leakdouble delete

The lesson

Local variables live on the stack and are destroyed automatically at the end of their scope. Objects created with new live on the heap until someone calls delete. The heap allows objects to outlive their scope and to be large, but someone must be responsible for freeing them.

Manual memory management fails in predictable ways: forgetting delete leaks memory; deleting twice corrupts memory; using an object after delete reads freed memory; an exception between new and delete skips the delete.

Modern C++ avoids raw new and delete in application code. Containers manage memory for collections, and smart pointers manage individual heap objects.

Step by step

  1. Allocate an object with new and forget to delete it; run with AddressSanitizer's leak check.
  2. Delete it twice and read the report.
  3. Throw an exception between new and delete and observe the leak.
  4. Replace the raw pointer with a local object or a container.

Practice activity

Find every ownership bug in a provided program using AddressSanitizer and list them before fixing anything.

Expected result: A list of leaks, double deletes and dangling uses, each with the sanitizer evidence.

Check your understanding

  1. When is a heap object freed?

    Show answer

    Only when delete is called (or a smart pointer releases it).

  2. Why can an exception cause a leak with raw new/delete?

    Show answer

    It can skip the delete statement.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.