I'm wondering if a C pointer can point to a value in an inner block and then dereference the pointer after the inner block ends?
#include <stdio.h>
int main() {
int a = 42;
int *r;
{
int b = 43;
r = &b;
}
int c = 44;
printf("%d\n", c); // Output: 44
// Is this OK?
printf("%d\n", *r); // Output: 43
return 0;
}
Am I getting the output "43" by luck or by design? Does C language specification say something about this situation? (Note that I'm not asking what a specific C compiler behaves)
This is not allowed. You were "lucky" you got an output of 43.
The lifetime of b ends after the scope it which it was declared ended, and accessing a variable whose lifetime has ended triggers undefined behavior.
This is described in section 6.2.4p2 of the C language:
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With