是否可以在递归C++函数中捕获stack overflow exception?如果是这样,怎么办?

所以在这种情况下会发生什么

void doWork()
{

     try() {

     doWork();
     }


     catch( ... )  {

     doWork();
     }
}

我不是在寻找特定操作系统的答案。就一般而言

最佳答案

本身也不异常(exception),但是如果您只想将堆栈使用量限制为固定数量,则可以执行以下操作:

#include <stdio.h>

// 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;
}

10-06 10:22