I believe you are looking for:
a way to control how memory is being allocated on the stack, at least in the context of not overwriting already-used memory
Of course, that's taken care by the OS! The low level system calls will make sure that a newly created automatic variable will not be written upon an already used memory block.
In your example:
for (int i = 0; i < 5; i++) {
int nums[5];
...
}
this is not the case, since nums
will go out of scope, when the i-th iteration of the for loop terminates.
As a result, the memory block nums
was stored into during the first iteration, will be marked as free when the second iteration initiates, which means that when nums
of the first iteration is going to be allocated in the stack, it will not be aware of any existence of the nums
of the first iteration, since that has gone already out of scope - it doesn't exist!