Dynamic Memory
So far, every variable you've declared had its size decided at compile time — you write int arr[100]; and the compiler bakes that 100 right into your program. But what if you don't know how many elements you'll need until the program is already running? What if a user wants to store 5 items today and 50,000 tomorrow? You can't just hardcode that. This is where dynamic memory allocation enters the picture — you're asking the operating system at runtime: "Hey, can I borrow some memory?"
This week is all about understanding where your data lives and how to manage memory yourself. First, we'll explore the two zones of memory your program uses — the stack (fast, automatic, but small) and the heap (big, flexible, but you're in charge of cleanup). Think of the stack as your desk and the heap as a giant warehouse — you can grab as much space from the warehouse as you want, but nobody's cleaning up after you.
Then we'll dive deep into the C way of managing memory: malloc() to request memory, free() to give it back, plus calloc() for zero-initialized blocks and realloc() to resize on the fly. These are the classic tools — and understanding them is essential because they're the foundation that C++ builds on. Once you've got the C approach down, we'll look at how C++ improves things with new and delete, which are cleaner and type-safe.
Finally, we'll cover the three deadly sins of memory management: memory leaks (forgetting to free), dangling pointers (using memory after freeing), and double free (freeing the same memory twice). Master these, and you'll avoid the most common bugs in C/C++ programming.
| Concept | What It Means | Why It Matters |
|---|---|---|
| Stack memory | Auto-managed, fast, small | Local variables live here — cleaned up automatically |
| Heap memory | Manual, large, flexible | Dynamic data lives here — YOU must free it |
malloc / free | C functions for heap allocation | The foundation of dynamic memory in C |
calloc / realloc | Allocate zeroed memory / resize | Extended C memory toolkit |
new / delete | C++ operators for heap allocation | Type-safe, calls constructors/destructors |
| Memory leak | Allocated memory never freed | Program slowly eats RAM until it crashes |