If you have a variable, there is a memory address associated with that variable, and in the case of a pointer variable, the “value” of that memory address is a reference to the memory address that holds the actual data that the pointer points to.
so if I have:
for (int x = 0; x < 2; x++)
{
char * a = (char*)malloc(20);
printf("%p\r\n", &a);
printf("%p\r\n", a);
}
the output should be something like:
00999999
04427310
00999999
0442ECF0
And as you can see, the 1st and the 3rd memory address remain the same for the pointer variables declared during each pass of the loop, and my understanding is that this is so because the previous variable went out of scope and the next available address is the same address.
Can this generalization be extended to all variables declared inside a loop or are there exceptions?
That’s how a stack usually works. And this is independent of variable type. When the stack grows downwards it might look more or less like this
The compiler assigns space on the stack to each variable relative to some base register. When the scope of the loop ends, the space for
aeffectively becomes “free” and can be reused.If there’s a second loop later or some other nested scope
bmight reuse the space previously occupied bya, since it is not needed anymore for a. This all depends on how the compiler optimizes the space on the stack.This is how it works for compiled C like languages at least. There are other memory models as well, of course.