Why is factorial not overflowing the stack in Erlang?

后端 未结 1 1676
一整个雨季
一整个雨季 2021-01-13 02:25
-module(demo).
-export([factorial/1]).

factorial(0) -> 1;
factorial(N) -> 
    N * factorial(N-1).

The factorial is not tail recursive but w

相关标签:
1条回答
  • 2021-01-13 02:50

    An Erlang process's "stack" is not stored in the stack given by the system to the process (which is usually a few megabytes) but in the heap. As far as I know, it will grow unbounded until the system refuses to give the VM more memory.

    The size includes 233 words for the heap area (which includes the stack). The garbage collector increases the heap as needed.

    The main (outer) loop for a process must be tail-recursive. Otherwise, the stack grows until the process terminates.

    Source

    If you monitor the Erlang VM process in an process monitor like Activity Monitor on OSX or top on other UNIX-like systems, you'll see that the memory usage will keep on increasing until the calculation is complete, at which point a part of the memory (the one where the "stack" is stored) will be released (this happens gradually over a few seconds after the function returns for me).

    0 讨论(0)
提交回复
热议问题