I was taught that variables within scope are destroyed (freed/de-allocated?) at the instruction generated by the "}" at the end of a scope body. I was about to teach someone the same thing, but I decided to see for myself, what will happen if I change a local variable through a pointer like this:
int main ()
{
int* p = NULL;
if(1)
{
int localvar = 1;
p = &localvar;
}
(*p) = 345;
printf("%i\n", *p);
return 0;
}
Compiled with MinGW-GCC and "-Wall -g -pedantic -w -Wfatal-errors -Wextra"
(even though -Wall
overrides most flags)
It was very surprising to me that not only a warning was generated, but also no runtime exception was thrown. Instead, everything seems to work just as if I am accessing a global variable.
Can this be explained in a definitive manner to avoid any future misconceptions?