C Programming

Lesson 6 of 11

Stack and Heap

Every running C program has two very different places to put data: the stack and the heap. Understanding the difference is essential once your programs get bigger than a single function.

The stack

Local variables live on the stack, memory is claimed automatically when a function is called and freed automatically the instant it returns:

C

The stack is extremely fast (allocating is just moving a pointer), but limited in size (usually a few MB) and strictly scoped, you can never return a pointer to a local stack variable and use it after the function returns, that memory is gone.

The heap

The heap is a much larger pool of memory that you manage manually, with malloc and free:

C

Heap memory survives until you explicitly free it, which is exactly what makes it useful for data that needs to outlive the function that created it, and exactly what makes it dangerous: forget to free and you leak memory, free twice or use it after freeing and you get undefined behavior.

StackHeap
Managed byThe compiler, automaticallyYou, manually (malloc/free)
SpeedVery fastSlower
SizeSmall, fixedLarge, limited by system RAM
LifetimeEnds when function returnsUntil you free it

WARNING

Forgetting to free heap memory is a memory leak. This is exactly the problem garbage collectors exist to solve, and exactly what you'll build one for later in this course.

📝 Stack and Heap Quiz

Passing score: 70%
  1. 1.Which memory region is automatically reclaimed the instant a function returns?

  2. 2.Memory allocated with malloc() must be freed manually with free(), it is not reclaimed automatically.

  3. 3.Forgetting to free heap memory that is no longer used is called a memory ____.