I'm trying to better understand block scope in C and whether the standard provides any guarantees regarding popping stack elements upon exiting block scope that may have been pushed to the stack upon entering that scope. As an example, does jumping to a label outside of a block (which is just, well, jumping to a label in C, nothing special there) after having declared a variable within that block result in a corrupted stack?
Here's a contrived example, and if it helps to further define the question, assume -O0
. My confusion is around whether err2
is popped from the stack when the execution path that jumps to the fatal
label is hit. Because labels are nothing special in C, I'd hypothesize that err2
isn't popped from the stack, and that stack corruption would result.
void foo()
{
int err;
if (err = baz()) {
printf("error %i", err);
int err2;
if (err2 = another_thing())
goto fatal;
}
printf("done");
return;
fatal:
printf("there was a fatal error");
}
Not possible to answer for certain; however most compilers allocate all the memory for the function at once.
As a practical matter, if it's gone out of scope, accessing a pointer to it is a bad idea and otherwise you don't care. Even at -O0
, the memory for an out-of-scope variable might be reused.
In no case will the local variables leak. The stack will not become imbalanced. There is nothing dangerous in the code in the question.