1

If there is a function like:

int func1() {
    int status = func2();

    // Do something with status.

    return status;
}

In the course of this function a variable status of type int is allocated memory and during the course of the function the variable is used and then returned from func1.

My question is, when is the memory garbage collected for this primitive, or does it remains in memory for ever?

Ankit Zalani
  • 3,068
  • 5
  • 27
  • 47

2 Answers2

2

In your example, status variable is allocated in the stack and will be freed immediately after func1 returns.

Jun Guo
  • 484
  • 1
  • 3
  • 14
2

The memory is allocated from the stack. When the function is called the stack pointer will be incremented enough to hold the function parameters, locals, return value (possibly), and return address. When the function returns, the stack pointer is decremented by exactly the same amount and control resumes at the return address.

In other words, the status declaration would cause the stack pointer to be incremented an extra sizeof(int) bytes (possibly more if the compiler decides to for the sake of alignment).

cdhowie
  • 158,093
  • 24
  • 286
  • 300