How to increase recursion depth limit (stack size limit)?

Most of the programming language has feature to increase limit of recursion depth (python => sys.setrecursionlimit, ruby => RUBY_THREAD_VM_STACK_SIZE). How to do this with Crystal?

Specifically, I want this code to be compiled and run without error.

def foobar(depth)
  return true if depth == 5000000
  foobar(depth + 1)
end
p foobar(0) # => true

https://play.crystal-lang.org/#/r/b21o

Hi!

Do you know of any language that compiles to native code that allows this?

There is no explicit recursion depth limit. Your code simply exceeds the stack size (which is 8MB) and there’s no more room on the stack for the program to continue further.
Changing the stack size is technically possible, but I don’t think it’s a good idea because it affects all fibers and thus heavily increases the overall memory use. It’s probably better to refactor the code to avoid such deep recursion.

1 Like

I believe (plz someone correct mt if I’m wrong) this is set by the OS, Crystal runtime just catch a signal and translate into an exception, so this post can help you:

TL;DR;
ulimit -s shows the stack default size
ulimit -s 16384 set the stack size to 16M.

3 Likes

FWIW in release mode this runs just fine because LLVM recognizes this can be tail-recursion:

$ crystal run --release tmp.cr
true
3 Likes

Crystal’s runtime allocates a stack for each fiber. And that stack size is managed by crystal, not the OS.

But I don’t think the main stack is managed by us. And in the OP example it’s the main stack.

Yeah, indeed. The stack size of the main fiber can be adjusted by ulimit -s.

2 Likes

ulimit -s solved my problem. Thank you very much.