Search code examples
schemeracketstack-overflow

Will this produce stack-overflow?


Following code of recursive function gives output of integers (both positive and negative) going up to infinity. Will it finally lead to stack overflow? Otherwise, how will computer finally crash?

(define(f)
  (let loop ((i 0))
     (printf "~a, ~a, "  i  (- -1 i))
     (loop (add1 i))))

Output of (f) :

0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, -14, 14, -15, 15, -16, 16, -17, 17, -18, 18, -19, 19, -20, 20, -21, 21, -22, 22, -23, 23, -24, 24, -25, 25, -26, 26, -27, 27, ....

Solution

  • Because Scheme has guaranteed tail call optimization your code will never produce a stack overflow.

    When i has become so large that it consumes a substantial part of the available memory your program will stop from a out of memory error since you are out of heap space. Before that you are probably expreicening your machine to have started using virtual memory and is swapping disk pretty heavily and probably very very slow at responding to anything. On my machine, since we have two almost same size at any given moment, I guess i would be up in about 14 billion decimal digits before it fails.