A common practice for compilers is to allocate memory for all auto variables of a function at the function’s entry point, simply by decrementing the stack pointer by the size of all the variables.
This is an easy way to handle all forms of block exits, especially in cases where "goto" is used.
So, in general, when control exits a block but stays within the function, the memory occupied by "auto" variables that have become inaccessible is not freed and retains the values of those variables.
Look at this example, which works with gcc and msvc. It is, we all agree, bad practice, and may not works with other compilers:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int v1;
int *p;
v1 = 123;
{
int v2;
p = &v2; // Keeps track of v2 memory
v2 = 321;
printf("v1=%d v2=%d\n", v1, v2);
}
// Access to v2 memory, which is out of scope,
// still prints the good value: "*p=321
printf("*p=%d\n", *p);
return EXIT_SUCCESS;
}
Once again, this example is ONLY for knowledge: DO NOT APPLY THIS IN SCHOOL OR PROFESSIONNAL WORK.
autohas a weird and dangerous meaning. Not to be confused with variables with automatic storage duration.