Question C

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? } 
+4
source share
3 answers

No, this is not so, b goes out of scope, access to it (via a pointer) is undefined behavior.

+11
source

As often happens, the question you ask does not really concern the scope, but most likely the life of the object. The lifetime of an array object b ends at the end of the if block, and any attempts to access it after that lead to undefined behavior.

In fact, speaking in pedantic language, it is even more about a than about b : as soon as the lifetime of b ends, the value of a becomes undefined. An attempt to "do something" that relies on an undefined pointer value results in undefined behavior.

+3
source

Its behavior is undefined - the duration of the obect step declared in the inner region (for example, b here) continues until the end of the block in which it was declared.

+1
source

Source: https://habr.com/ru/post/1299168/


All Articles