Catching “Stack Overflow” exceptions in recursive C++ functions

前端 未结 11 1236
暖寄归人
暖寄归人 2020-12-01 16:34

Is it possible to catch a stack overflow exception in a recursive C++ function? If so, how?

so what will happen in this case

void doWork         


        
11条回答
  •  甜味超标
    2020-12-01 17:15

    It's not an exception per se, but if you just want to be able to limit your stack usage to a fixed amount, you could do something like this:

    #include 
    
    // These will be set at the top of main()
    static char * _topOfStack;
    static int _maxAllowedStackUsage;
    
    int GetCurrentStackSize()
    {
       char localVar;
       int curStackSize = (&localVar)-_topOfStack;
       if (curStackSize < 0) curStackSize = -curStackSize;  // in case the stack is growing down
       return curStackSize;
    }
    
    void MyRecursiveFunction()
    {
       int curStackSize = GetCurrentStackSize();
       printf("MyRecursiveFunction:  curStackSize=%i\n", curStackSize);
    
       if (curStackSize < _maxAllowedStackUsage) MyRecursiveFunction();
       else
       {
          printf("    Can't recurse any more, the stack is too big!\n");
       }
    }
    
    int main(int, char **)
    {
       char topOfStack;
       _topOfStack = &topOfStack;
       _maxAllowedStackUsage = 4096;  // or whatever amount you feel comfortable allowing
    
       MyRecursiveFunction();
       return 0;
    }
    

提交回复
热议问题