Lesson 080

Memory Management Basics

Stack & Heap · Allocation · Fragmentation

1:00

How programs allocate and release heap memory, what goes wrong when they do not, and how allocators decide where to place each block.

By the end, you can

  • Draw the four regions of a process's address space (text, data/BSS, heap, stack) and state the growth direction of the stack and heap — they grow toward each other, the stack downward and the heap upward.
  • Explain the difference between stack and heap allocation in terms of lifetime, allocation speed, and who manages the memory (automatic scope-based vs. manual/explicit).
  • Write a correct malloc/free sequence: allocate, check the result for NULL, use only in bounds, free exactly once, and null out the dangling pointer.
  • Define memory leak and explain its long-term effect on a running program.
  • Distinguish external fragmentation from internal fragmentation with a concrete example.
  • Explain why compaction cannot be applied to raw C malloc pointers.
  • Compare first-fit, best-fit, and worst-fit placement strategies and identify which tends to minimize external fragmentation versus which is fastest to place.
  • Describe use-after-free, double-free, and buffer overflow, explain why each is dangerous (corruption or exploitable undefined behavior), and name a practice that prevents it.
Up next in Math, Memory & Files
Questions or feedback?