Maximum call stack size exceededWhat is "Maximum call stack size exceeded"?
A function kept calling itself and never stopped, until the stack ran out of room. On a laptop it is a segmentation fault. Find the missing stop.
What the runtime is telling you
RangeError: Maximum call stack size exceededEvery function call gets a stack frame: a little block of memory for its parameters and local variables. The frame is freed when the function returns. A function that calls itself (recursion) stacks up one frame per call. If it never stops calling, the frames pile up until there is no room left, and the program is stopped. Some browsers say too much recursion; on a laptop it is usually a Segmentation fault, or simply stack overflow.
A recursive function needs a base case: an input where it returns without calling itself again. Each call must also move closer to that case.
How to find it
Look for a function that calls itself. Find its base case and check two things: does the condition ever become true, and does every call change the argument in the right direction? A test like n == 0 is never reached if n starts negative or goes down by 2 from an odd number. Adding printf("n=%d\n", n); at the top shows the numbers running away.
Run it: a countdown with no floor
Press Run and read the error from the bottom up.
#include <stdio.h>
int countdown(int n) {
if (n == 0) {
return 0;
}
return 1 + countdown(n - 2);
}
int main(void) {
printf("steps from 10: %d\n", countdown(10));
printf("steps from 7: %d\n", countdown(7));
return 0;
}
Lives that never run out
total_lives(level) adds up the bonus lives from every level from level down to 1: level k gives k lives. Level 4 should give 4 + 3 + 2 + 1 = 10. It crashes instead. Fix the recursion so it prints total 10.
#include <stdio.h>
int total_lives(int level) {
if (level == 0) {
return 0;
}
return level + total_lives(level + 1);
}
int main(void) {
printf("total %d\n", total_lives(4));
return 0;
}