Question: Question:
I think that the memory area allocated by the program includes the stack area and the heap area.
The stack area is an area secured by variables defined in functions, etc.
The size of the memory is decided at the time of compilation, and it is up to the OS to secure and release it.
On the other hand, the heap area is an area allocated by dynamic allocation (malloc or new).
It will remain there unless the programmer releases it.
I have a question here (please point out if the above interpretation is incorrect).
For example, if you have the following code (C ++):
void Hoge()
{
int hoge1 = 0;
for( int i = 0; i < 10; ++i ){
hoge1+=i;
}
}
Here, I think that both the variable hoge1
and the variable i
in the for statement are secured in the stack area.
Also, the scope of the variable i
is only in the for statement and cannot be accessed from others.
The question is, does the variable i
remain in memory when the for statement is exited?
What you want to know is that the smaller the scope of a variable, the smaller it is.
Is it a memory saver?
Thank you.
Answer: Answer:
Does the variable i remain in memory when the for statement is exited?
It remains in most cases. Normally, the stack is increased or decreased when entering and exiting the function. As BLUEPIXY commented, the possibility of increasing or decreasing the stack according to the scope is not zero, but increasing or decreasing the stack is not an inexpensive operation, so it is not realistic to do it in units of scope.
What you want to know is that the smaller the scope of a variable, the more memory it saves.
The example question doesn't save you, but it can in essence. Consider a code like the one below.
void Foo() {
int bar = 0;
for (int i = 0; i < 10; ++i) {
bar += i;
}
for (int j = 10; j > 0; --j) {
bar += j;
}
}
The i
used in the first half of the loop and the j
used in the second half of the loop have separate scopes and are independent of each other. In such cases, there is room for the compiler to make such optimizations by using / reusing the same memory area for i
and j
to reduce the total amount of stack memory used by this function.