Could the stack become fragmented due to closures being allocated and not deallocated after a function returns?
Closures are essentially stack frames that persist after a function completes execution, similar to a 'stack frame' on the heap rather than the stack itself.
For example, if both foo() and bar() are closures called one after another, is there a scenario where foo()'s closure could be deallocated while bar() still needs space on the stack?
If this process repeats, it could lead to stack fragmentation similar to heap fragmentation, but since stacks work differently, the space would simply be lost. However, this does not seem to occur in practice. What prevents it from happening?
I am particularly interested in JavaScript, where the underlying machine is unknown, but this question applies to any functional language.
To simplify the question...
Consider the code snippet below.
outer = function() {
var foo = function(v) {
return function() { return v; }
}
var bar = function(w) {
return function() { return w; }
}
var f = foo(5);
var b = bar(7);
document.writeln(f());
document.writeln(b());
document.writeln(f());
document.writeln(b());
}
outer();
https://i.sstatic.net/RLYIS.png
Sequence of events: outer() is called. The return address is saved on the stack. Functions like foo
, bar
, f
, and b
are hoisted and allocated on the stack when outer()
is invoked. When foo()
is called with parameter 5
, its local variables and the returned anonymous function are also stored on the stack. The same occurs for b
and bar
. Even though the anonymous function inside foo()
forms a closure by referencing an enclosing variable, my main query is: How do we ensure that f
and foo()
don't get deallocated while b
and bar()
remain active, potentially causing an empty and inaccessible stack fragment?