Search code examples
c++stack-overflowgotodestroycallstack

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.


Solution

  • 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