(I believe this question is technically distinct from Can a local variable's memory be accessed outside its scope? because it is C instead of C++.)
I know that in C you can put a local variable in a block and it will be scoped to that block:
#include <stdio.h>
int main() {
{
int x = 5;
printf("x = '%d'\n", x);
}
// can't see x anymore
}
My question is, is it nonetheless still SAFE to use that memory until the end of the function? Whether it is WISE from a design / coding practices perspective is a separate question, but is it undefined behavior or can I count on that memory staying put? For example:
#include <stdio.h>
int main() {
int *ptr;
{
int x = 5;
printf("x = '%d'\n", x);
// hold on to a ptr while we still know the address
ptr = &x;
}
// can't see x anymore, but is this safe?
printf("still have a ptr! '%d'\n", *ptr);
}
Thanks!