Josh
Josh

Reputation: 19

Taking the address of a variable within a loop in C

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

Answers (3)

Mario Ishac
Mario Ishac

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

tmlen
tmlen

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

John3136
John3136

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

Related Questions