When executing a goto
statement in C++, are the two arrays in the code fragment below removed from the stack? Or will they be removed from the stack when the method returns?
retrySplit:
...
uint32_t primsAbove[primitives.size()];
uint32_t primsBelow[primitives.size()];
...
goto retrySplit;
This question is not related to leaks resulting from using a goto statement, but concerned with the possibility of whether you can blow up your stack.
This program:
#include <iostream>
class X {
public:
X() { std::cout << "ctor" << std::endl; }
~X() { std::cout << "dtor" << std::endl; }
};
int main(int argc, char** argv) {
int i = 0;
label:
X a;
if (i == 0) {
i = 1;
goto label;
}
return 0;
}
Produces this output:
$ ./a.out
ctor
dtor
ctor
dtor
Yes, the arrays are destroyed. [stmt.jump]/2:
On exit from a scope (however accomplished), objects with automatic storage duration (3.7.3) that have been constructed in that scope are destroyed in the reverse order of their construction. […] Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.
You can also verify this through the following snippet:
#include <iostream>
struct A
{
A() {std::cout << "A";}
~A() {std::cout << "D";}
};
int main()
{
int counter = 0;
label:
if (counter++) // Exit on second run.
return 0;
A a;
goto label;
}
Demo. Your output should be AD
.
Note also that counter
is not destroyed when jumping back to label
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With