Stack vs Heap Memory in C

// Quick Answer
  • Stack is used for static memory allocation (automatic).
  • Heap is used for dynamic memory allocation (manual).
  • Stack is fast but limited; heap is flexible but slower.

What is stack memory?

Stack memory is a region of memory used for automatic storage such as function calls, local variables, and control flow.

💡 Simple idea

Stack works like a stack of plates — last in, first out (LIFO).

What is heap memory?

Heap memory is a large pool of memory used for dynamic allocation during runtime.

It is managed manually using malloc, calloc, realloc, and free.

Stack vs Heap comparison

Feature        | Stack                     | Heap
------------------------------------------------------------
Allocation     | Automatic                | Manual
Speed          | Very fast                | Slower
Size limit     | Small                    | Large
Management     | OS handles it           | Programmer handles it
Lifetime       | Function scope          | Until freed manually

Stack example

void func() {
  int x = 10;   // stored in stack
}

Heap example

int *ptr = (int*) malloc(sizeof(int));
*ptr = 10;
free(ptr);

How stack works

  • Memory is automatically allocated when function is called
  • Freed when function ends
  • Uses LIFO order

How heap works

  • Memory is allocated manually
  • Persists until explicitly freed
  • Used for dynamic data structures
📌 Real-world fact

Most crashes in C programs happen due to incorrect heap memory handling (like memory leaks or double free errors).

When to use stack

  • Small, temporary variables
  • Function-local data
  • Fast execution needed

When to use heap

  • Large or unknown data size
  • Dynamic data structures
  • Data that must persist after function ends

Summary

Stack memory is fast and automatically managed but limited in size. Heap memory is flexible and powerful but requires manual management.