Stack memory holds local variables and is allocated and freed automatically as functions are called and return. It is fast but small. Heap memory is requested with malloc and friends, can be large, and survives until free, so it can be returned from a function.
Remember
void f(void) {
int s[100]; /* stack: gone on return */
int *h = malloc(100 * sizeof *h); /* heap: lives until free */
free(h);
}
Reference
Cheat Sheet
Keep these facts handy while you work with Stack and Heap Memory in C.
Topic
Detail
Stack
Automatic, fast, limited size
Heap
Manual, slower, large
Return data
Heap or static data can outlive a function
Failure
Stack: overflow; heap: NULL from malloc
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: malloc() Function.
Example 1 — Returning heap data from a function
A stack array would vanish; the heap array survives.
C
#include <stdio.h>
#include <stdlib.h>
static int *make_array(int n) {
int *a = malloc(n * sizeof *a);
if (!a) return NULL;
for (int i = 0; i < n; i++) a[i] = i * 10;
return a;
}
int main(void) {
int *data = make_array(4);
if (!data) return 1;
printf("heap array:");
for (int i = 0; i < 4; i++) printf(" %d", data[i]);
printf("\n");
free(data);
return 0;
}
Output
heap array: 0 10 20 30
How It Works
make_array allocates on the heap, so the data outlives the function.
A local int a[4] returned by address would dangle.
The caller owns the memory and must free it.
Edge Cases & Pitfalls
Check these before relying on Stack and Heap Memory in real programs.
own
Unclear ownership
Document who frees returned pointers. A common rule: the allocator's caller frees.
overflow
Deep recursion
Each recursive call uses stack space; very deep recursion causes stack overflow.
Remember
Key Takeaways
Stack: scope-bound.
Heap: you manage it.
Return: heap data can be returned safely.
One line: Stack memory holds local variables and is allocated and freed automatically as functions are called and return.
Frequently Asked Questions
Stack allocation just moves a pointer and is much faster. Heap allocation runs allocator code and may fragment memory.
It happens when the stack runs out of space, usually from infinite or very deep recursion or from huge local arrays.
Continue with "C malloc() Function" next. Allocate a block of uninitialized memory from the heap. The C Dynamic Memory Allocation hub lists every topic in order.