Dynamic Memory Allocation Basics
What you'll learn: How to request memory from your program while it's running, and understand where that memory lives.
The Problem with Fixed-Size Variables
Until now, every variable you've declared has lived on the stack — a fast, automatically-managed region of memory. The catch? You must know the size at compile time. What if you don't know how much data you'll need until the program is running?
Enter the Heap
Dynamic memory allocation lets you request memory from the heap — a large, flexible pool — while your program runs. Think of the stack as a neat, organized desk drawer (limited space, easy to manage), and the heap as a vast warehouse (lots of space, but you're responsible for tracking what you store there).
In C, you use malloc() to request heap memory:
int *ptr = (int *)malloc(5 * sizeof(int)); // Request space for 5 integers
In C++, you use new:
int *ptr = new int[5]; // Request space for 5 integers
Both return a pointer to the first byte of the allocated memory. If allocation fails (out of memory), they return NULL or throw an exception.
Key Differences: Stack vs Heap
- Stack: Automatic cleanup when variables go out of scope. Fast but limited.
- Heap: You control when memory is allocated and freed. Flexible but requires manual cleanup (
free()in C,deletein C++).
Key Takeaway: Dynamic memory allocation uses malloc/new to request memory from the heap at runtime, giving you flexibility at the cost of manual management — unlike stack variables that clean themselves up automatically.