A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
The call stack is a fixed-size region of memory. On Linux, it defaults to 8 MB. On Windows, 1 MB. Every function call pushes a frame onto it. Every return pops one. If the stack pointer moves past the allocated region, the CPU hits a guard page and the OS delivers a segmentation fault. The message says "Segmentation fault" or "Stack overflow" depending on the platform. The cause is almost always one of three things: infinite recursion, very deep recursion, or enormous local arrays.
We saw this in the recursion basics lesson. Missing base case, or a base case that is never reached because the reduction step does not converge. The fix is always the same: verify that every recursive path reaches the base case in finite steps.
#include <stdio.h>long deep_sum(long n) {if (n == 0) return 0;return n + deep_sum(n - 1);}int main(void) {printf("Result: %ld\n", deep_sum(1000000));return 0;}
One million frames. Each frame is roughly 32 bytes (return address, saved registers, the parameter n). That is 32 MB, well beyond the 8 MB default stack. The recursion is correct. The base case is reached. But the depth exceeds the available stack. The fix: convert to iteration, increase the stack size with ulimit -s, or use an explicit stack on the heap.
Setting the stack to 64 MB (65536 KB) gives enough room. This is a band-aid. The real fix for production code is to avoid million-deep recursion. Use a loop. The iterative version uses O(1) stack space regardless of n.
#include <stdio.h>void process_data(void) {int buffer[2000000];buffer[0] = 42;printf("buffer[0] = %d\n", buffer[0]);}int main(void) {process_data();return 0;}
Two million ints is 8 MB. That single array consumes the entire default stack. There is no recursion involved. The fix: allocate large buffers on the heap with malloc, make them static, or make them global. The stack is for small, short-lived data. The heap is for large or long-lived data.
If you need an array larger than a few kilobytes, allocate it with malloc. Stack space is precious and finite. Every function in the call chain shares the same stack. A large local in a deeply nested call is a stack overflow waiting to happen.
Stack overflows are deterministic. They crash at the same depth every time for the same input. That makes them easier to diagnose than heap corruption. The fix is almost always architectural: reduce depth, move data to the heap, or convert recursion to iteration. Next: direct vs indirect recursion, where the call chain loops through multiple functions.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.