Stack and heap
- C course
- Beginner
- Lesson 100/116
- 5 min
Learn the difference between stack and heap memory.
Stack and heap: two memory regions
C programs split memory into two main regions. The stack holds local variables; it is cleaned automatically when a function returns. The heap is memory you allocate with malloc; you release it with free.
int a = 10; /* stack */
int *p = malloc(4); /* heap */Where a variable lives depends on how you declare it. The stack is fast but small; the heap is large but you manage it. Knowing this distinction is the basis for understanding pointer and memory errors.
How the stack works
The stack grows and shrinks with function calls. When a function is called, its local variables are pushed onto the stack; when it returns, this space is released.
void f(void) {
int x = 5; /* on the stack */
}
/* when f returns, x is gone */This is why returning the address of a local variable is dangerous; that address is no longer valid. The stack is fast but has limited capacity; deep recursion can cause a stack overflow.
Practice Access a local variable via pointer
Declare int a = 10 (on the stack). Declare an int * pointer that points to a. Print the value the pointer points to with printf.
Starter code
#include <stdio.h>
int main(void) {
int a = 10;
// Define a pointer to a; print the pointed value with printf
return 0;
}Sample solution
int *p = &a;
printf("%d\n", *p);Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is the local variable int a = 10; stored?
- Stack Correct answer
- Data segment
- Heap
- Register
Explanation: Local variables live on the stack.
2 Match region to property
| Term | Meaning |
|---|---|
Stack |
Local variables |
Heap |
Allocated with malloc |
free |
Releases heap memory |
automatic |
Cleared on function return |
3 Fill in the blank: pointer declaration
int a = 10;
____ *p = &a;
int a = 10;
int *p = &a;
Explanation: int *p declares a pointer to a.