How long is the data allocated to functions?

5

In a language, (I do not know if it has any difference in others, but I may consider JavaScript) when I have this situation:

function a() {
    b();
}

function b() {
    c();
}

function c() {
    d();
}

function d() {
    e();
}

function e() {
    f();
}

function f() {

}

What happens to the things that are being created within the methods? As it runs it will free up memory or does it hold up to the F execute method?

    
asked by anonymous 06.04.2016 / 15:25

1 answer

4

First nothing is being executed within these functions. There is memory allocation, so there is no need to release it.

If the example has some variable being allocated, at the end of the execution of each function, the content is released. Not the space occupied in memory, since the memory is pre-allocated. Local function variables are placed in the stack . Then each function call goes up on the stack, and in the end it goes back to the original position.

Then everything that is allocated in a, b, c, d, and will be kept already technically these functions are running, they only delegated temporarily to another function. As each one of them ends it is releasing. The name stack is just to identify it well. You can not release what's underneath to take something out of the pile that is not at the top just by taking what's up.

The stack exists regardless of whether or not to use it (it's impossible not to use it on anything that does something minimally useful). The space allocated to the stack is fixed, using or not. If it exceeds stack space, the famous stack overflow occurs.

In general, all languages work like this.

If there is any allocation in heap (see link above) it will not be released. The heap memory release strategy varies from language to language. Some require the programmer to do this, some do it more or less automatically, some do it perfectly, others do it to some extent. In general goes in heap which is too large for the stack or that needs to survive the end of the function .

    
06.04.2016 / 15:36