Reputation: 19
Is this valid or does it have undefined behavior:
#include <stdio.h>
int main(){
int *a = NULL;
for (int i=0; i<1; i++){
int b = 6;
a = &b;
}
printf("%d\n", *a);
return 0;
}
Isn't it possible for b
to be removed from the stack once it's out of the loop (and hence out of scope)?
Upvotes: 1
Views: 69
Reputation: 5877
You're right, that will be undefined behavior. If you want to capture the value of b
outside the for-loop, you can do *a = b
inside the for-loop, but a
will have to point to somewhere non-null prior in order for this to work.
Upvotes: 3
Reputation: 9092
It is undefined behavior.
The variable b
has automatic storage duration: its storage is deallocated at the end of the block it is declared in, that is the }
of the for
loop.
Then a
becomes a danging pointer. Applying the dereference expression *a
is undefined behavior in this case.
https://en.cppreference.com/w/c/language/storage_duration
https://en.cppreference.com/w/c/language/operator_member_access
Upvotes: 3
Reputation: 29266
Yes. That is undefined behavior once you get out of the loop.
a
is pointing to an address that has gone out of scope and so is not usable.
Upvotes: -1