I have a question about scoping rules in C that can best be illustrated by the following code:
#include <stdio.h>
int main(void)
{
int * x = NULL;
{
int y = 42;
x = &y;
printf("%d\n", *x);
}
printf("%d\n", *x);
*x = 74;
printf("%d\n", *x);
return 0;
}
Running this code prints out
42
42
74
I've compiled it using clang with all warnings and with -fsanitize=undefined
.
The variable y
is declared in a local scope, and is inaccessible after the closing brace. Nonetheless, we can make a previously-declared pointer refer to that local variable, and we can refer to the contents of that memory even after its scope ends.
While this code might work due to the peculiarities of how the program stack works on my machine, it seems to me that dereferencing x
at this point should be undefined behavior. I have a better feel for how I'd answer this question in C++. If we were using some class with a non-trivial destructor, rather than a basic type like int
, then its destructor will be called at the closing brace.
Does this code invoke undefined behavior? I don't know the C standard very well, so a citation on the relevant rule would be appreciated.