Reputation: 471
Consider the following code
int* a[5];
void f() {
int i = 50;
a[0] = &i;
}
void main() {
f();
printf("%d", *a[0]);
}
When i
goes out of scope, does it get unloaded, and the pointer becomes invalid, or does the value remain?
Upvotes: 0
Views: 38
Reputation: 18381
As per the C11 standard draft section 6.2.4 Storage durations of objects
...The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
Therefore the standard is explicitly stating that the value is not guaranteed to be preserved.
Upvotes: 3
Reputation: 409404
When the life-time of i
ends (as f
returns) any pointer to it becomes invalid and should not be dereferenced.
Any attempt to dereference invalid pointers leads to undefined behavior.
Upvotes: 2