Why is factorial not overflowing the stack in Erla

2019-02-18 06:36发布

问题:

-module(demo).
-export([factorial/1]).

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

The factorial is not tail recursive but why is it not overflowing the stack? I am able to get factorial of 100,000 without stack overflow but takes some time to compute.

回答1:

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).



标签: erlang