Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The effect of a goto statement in C++ on the stack

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.

like image 210
Matthias Avatar asked Dec 19 '22 09:12

Matthias


2 Answers

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
like image 58
vz0 Avatar answered Dec 21 '22 23:12

vz0


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.

like image 40
Columbo Avatar answered Dec 21 '22 22:12

Columbo