tags:

views:

85

answers:

3
+2  Q: 

C scope question

Is the following code valid

int main(){
int * a = 0;
if ( !a ) {
    int b[500];
    a = b;
}

//do something with a, 
//has the array a is 
//pointing too gone out
//of scope and garbage
//or is it still fine?
}
+11  A: 

No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.

nos
No? He asks: "has the array a is pointing too[sic] gone out of scope". That definitely should be a yes.
Charles Bailey
@Charles: "Is the following code valid?" "No, it is ... undefined behavior". Seems fine to me.
Stephen Canon
scope only matters for names -- for the space allocated (what `a` points to), what matters is the storage duration, which is the same in this case, but might not be in others.
Chris Dodd
@paxdiablo: Fair enough, it wasn't totally clear. I read the 'real' question as being in the comment.
Charles Bailey
+1  A: 

Its undefined behavior -- the stroage duration of an obect declared in an inner scope (such as b here) lasts up until the end of the block in which its declared.

Chris Dodd
+2  A: 

As it often happens, the question you are asking is not really about scope, but rather about lifetime of an object. The lifetime of b array object ends at the end of the if block and any attempts to access it after that lead to undefined behavior.

In fact, pedantically speaking, it is even more about a than about b: once the lifetime of b ends, the value of a becomes indeterminate. An attempt to "do something" that relies on the indeterminate value of a pointer leads to undefined behavior.

AndreyT
Really nice explanation.
Stephen Canon