Lesson 124 +10 XP

Memory Management

Memory Management

Every variable your program creates lives somewhere in the computer's RAM. Memory management is the art of using that memory correctly: asking for it when you need it, and giving it back when you're done.

The two big regions: stack and heap

C++ programs split their memory into two main areas:

  • The stack: small, fast, and automatically managed. Local variables and function calls live here. When a function returns, its stack memory is cleaned up by itself.
  • The heap: a large pool of free memory. You can grab as much as you want while the program runs, but nothing is cleaned up for you - you must do it manually.
int main() {
    int x = 5;              // x lives on the stack (automatic)
    int* p = new int(5);    // the int lives on the heap (manual)
    delete p;               // you must free it yourself
    return 0;
}

Why is manual management risky?

Forgetting to free heap memory causes a memory leak - memory that can never be used again. Freeing the same memory twice, or freeing it while something still points at it, causes worse bugs like crashes. That's why modern C++ is designed to take this burden off you.

The modern mindset

Modern C++ prefers working at a high level: use objects with automatic lifetimes, containers like std::vector, and smart pointers instead of juggling raw new and delete. Less manual bookkeeping means fewer bugs.

TL;DR

  • Memory has two big regions: the stack (automatic) and the heap (manual).
  • Stack memory is freed when a function returns.
  • Heap memory must be freed by you.
  • Manual mistakes cause leaks, crashes, or undefined behavior.
  • Modern C++ uses containers and smart pointers to avoid raw new/delete.