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?
}
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?
}
No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.
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.
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.