Dashboard/Block 2: C Essentials/Week 3
Week 3C Essentials

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.

ConceptWhat It MeansWhy It Matters
Stack memoryAuto-managed, fast, smallLocal variables live here — cleaned up automatically
Heap memoryManual, large, flexibleDynamic data lives here — YOU must free it
malloc / freeC functions for heap allocationThe foundation of dynamic memory in C
calloc / reallocAllocate zeroed memory / resizeExtended C memory toolkit
new / deleteC++ operators for heap allocationType-safe, calls constructors/destructors
Memory leakAllocated memory never freedProgram slowly eats RAM until it crashes

Learning Objectives

Understand the difference between stack and heap memory
Use malloc() and free() for C-style dynamic allocation
Use calloc() for zero-initialized allocation and realloc() to resize
Understand sizeof and why it matters for allocation
Identify and prevent memory leaks, dangling pointers, and double free
Use new/delete for C++ allocation and understand how it improves on malloc/free

Key Concepts

Stack vs Heap

malloc and free

calloc, realloc, and sizeof

Memory Pitfalls: Leaks, Dangling Pointers, Double Free

From C to C++: new and delete