gpt4 book ai didi

c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常

转载 作者:可可西里 更新时间:2023-11-01 15:33:44 25 4
gpt4 key购买 nike

是否可以在递归 C++ 函数中捕获 堆栈溢出异常?如果是,怎么办?

那么在这种情况下会发生什么

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

关于c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com