Effect of goto statement in C ++ on the stack

When executing a statement goto

in C ++, are the two arrays in the code snippet below the ones removed from the stack? Or will they be popped off 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 that result from using a goto statement, but is related to the possibility of being able to blow up your stack.

+3


source to share


4 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

      

+5


source


Yes, arrays are destroyed. [Stmt.jump] / 2:

When leaving the area of ​​action (no matter how it was done), objects with automatic (3.7.3) that were built in this area are destroyed in the reverse order of their construction. [...] Moving a loop, from a block or back behind an initialized variable with an automatic storage duration, includes destroying objects with an automatic storage time that is in the region at the point passed from, but not to the point translated to.

You can also check this with 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 way out should beAD

. Also note thatcounter

it is not destroyed when you switch tolabel

.

+4


source


Things are popped off the stack when they go out of scope (end up in the closing parenthesis), so it really depends on where your goto is going.

Also this is a bit of a side note, but why are you using goto? You should look for them because they are a little notorious.

+1


source


To remove from the stack and be alive are two different things. In your example, the memory on the stack for arrays can be preserved, however, after going to layout, the arrays will be considered non-living. That is, before the transition destructors for array elements are called, and when control reaches the array definitions, when the array element constructors are called.

+1


source







All Articles