Am I right in thinking that, in the following snippet, the automatic variables x and y will be reallocated on the stack on every pass of the while loop and never released, eventually leading to stack overflow? Will there also be 10 reallocations of z on each pass, before they are released after exciting from the scope of the inner while loop?
If this snippet is placed in a worker thread, will the stack be saved for re-entry after the thread has served its time allocation, i.e., will x and y never be deallocated?
while (1)
{
int x = 0;
int *y = &x;
while (x < 10)
{
int z = 0;
++x;
}
}
No, there’s no problem. The automatic variables can easily reuse the same space each time. Remember that the automatic variables’ lifetimes end at the end of the block, so they never live longer than one iteration.
(In fact, you would need a lot more code to construct something where each iteration used a different memory location — you’d have to keep an extra counter around and compute an offset each time!)