I made a small test to see how the stack is used in a C application.
#include <stdio.h>
void a(void)
{
int a = 0;
}
void b(void)
{
int b;
printf("%i\n", b++);
}
int main(void)
{
a();
b();
b();
b();
fflush(stdin), getc(stdin);
return 0;
}
Isn’t b allocated in the same place on the stack where a was? I would expect the output to be 0 1 2, but instead I get the same garbage value three times. Why is that?
I might guess that you got all zeroes as output, but this is not necessarily the case. In function b, you are declaring a new int b which is created for each execution of the code. B is uninitialized in your code, but some compilers will zero this value. This is not standard, and should NOT be counted on. You should always initialize your variables.
As far as the stack goes, that is implementation specific and dependent upon the compiler, optimizer settings, etc. There is no guarantee that this variable ever lives on the stack. Chances are it does not, given the short duration of scope it may just live in a CPU register.
In the above code b and a are completely independent variables, and thus should not be counted on to have the same value, even if they are stored in the same memory location.