/*
One way to get a stack overflow - recursion depth gets too large.
This program multiplies numbers by repeated addition, and adds by repeated increment.
This is a silly way to multiply numbers, but it is a recursive program that
will crash if the recursion depth gets too large.
*/
#include <stdio.h>
int recursion_depth, max_recursion_depth;
unsigned int add(unsigned int x, unsigned int y, int recursion_depth) {
if (recursion_depth > max_recursion_depth) max_recursion_depth = recursion_depth;
if (y == 0) return x;
return add(x, y-1, recursion_depth+1);
}
unsigned int mult(unsigned x, unsigned y, int recursion_depth) {
if (recursion_depth > max_recursion_depth) max_recursion_depth = recursion_depth;
if (y == 0) return 0;
if (y == 1) return x;
return x + mult(x, y-1, recursion_depth+1);
}
int main(int argc, char *argv[]) {
max_recursion_depth = 0;
recursion_depth = 0;
unsigned int a = (unsigned int) 78, b = (unsigned int) 1e5; // change this to 1e6 to get a stack overflow
printf("%u * %u = %u\n", a, b, mult(a, b, recursion_depth+1));
printf("max_recursion_depth = %d\n", max_recursion_depth);
return 0;
}