Phil
Phil

Reputation: 7566

Erlang - Looping and Memory Allocation

The typical way to make a loop for a process in Erlang is to use recursion:

keepAlive(someArg) ->
    % do something,
    keepAlive(someValue)

Since variables in Erlang are immutable, what happens when I declare a local variable inside such a loop? Does it get garbage collected on the next recursive call? Even without a declaration of new variables, aren't loops like this a problem and can cause a stackoverflow, because you get an endless number of pointers, from one loop to another, that theoretically might have to go all the way back at some point?

Upvotes: 2

Views: 368

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Technically speaking, local variables are not declared in Erlang. They are bound to value. Values of local variables are stored on the stack. Some data types could be stored directly in the stack and don't have to be allocated on the heap. So local variables don't have to be garbage collected but values of some data types have to be. Anyway, those values are not garbage collected in next recursive call but when heap meets stack which means heap is full and garbage collection is triggered.

Most importantly, if you write a function in the way you described stack frame is freed before the recursive call and parameter is stored in "registers". Then next recursive call is not function call but just jump. It means stack doesn't grow. All values which were allocated on the heap and no longer referenced by stack or function parameters can be garbage collected so there is not memory leak or stack overflow. In fact, it is very simple and elegant solution.

Upvotes: 2

Related Questions