Suppose I have a for
loop and a local variable inside it:
for(int i=0;i<10;i++){ // Outer loop
int p[10]; // Local variable
for(int j=1;j<10;j++){ // Inner loop
p[j] = p[j-1]+1;
}
}
When all the compiler optimisations are off, it is clear that for the first iteration of the outer loop, the an array p
will be allocated in the main memory.
But, is the memory allocated for p
freed in the main memory at the end of the first iteration of the Outer loop and allocated again after the start of the subsequent iterations of the Outer loop?
In my opinion, the scope of loops and the scope of methods differ. When function has been completely executed, the local variables are deallocated and the memory is returned back to the OS.
But for loop, when though the scope ends at the end of each iteration, the local variables are not deallocated as they are used in the near future (subsequent iterations). It is only after the loop ends it's execution, the local variables should be deallocated from the main memory.
Kindly correct me if wrong.