Catching quot;Stack Overflowquot; exceptions in recursive C++ functions(捕获“堆栈溢出递归 C++ 函数中的异常)
问题描述
是否可以在递归 C++ 函数中捕获堆栈溢出异常?如果是,怎么办?
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()
{
try() {
doWork();
}
catch( ... ) {
doWork();
}
}
我不是在寻找特定操作系统的答案.只是一般
I am not looking for an answer to specific OS. Just in general
推荐答案
这本身并不是一个例外,但如果您只想将堆栈使用限制在一个固定的数量,您可以这样做:
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 <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
", curStackSize);
if (curStackSize < _maxAllowedStackUsage) MyRecursiveFunction();
else
{
printf(" Can't recurse any more, the stack is too big!
");
}
}
int main(int, char **)
{
char topOfStack;
_topOfStack = &topOfStack;
_maxAllowedStackUsage = 4096; // or whatever amount you feel comfortable allowing
MyRecursiveFunction();
return 0;
}
这篇关于捕获“堆栈溢出"递归 C++ 函数中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:捕获“堆栈溢出"递归 C++ 函数中的异常
基础教程推荐
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
