frogstair
frogstair

Reputation: 471

Do values whose pointers are in arrays persist

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

Answers (2)

Eugene Sh.
Eugene Sh.

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

Some programmer dude
Some programmer dude

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

Related Questions