c - 计算阿克曼时如何检查堆栈使用情况

标签 c posix stack-overflow ackermann

我正在了解我的系统计算阿克曼算法的两个和三个参数版本的能力。对于非常小的 m 和 n 值,我的系统将计算并打印从 A0 和 A1 方法调用返回的结果。然而,任何高于 3 或 4 的值都不会返回并卡住我正在使用的 atm 终端。我的问题是我确实确定了我的机器可以计算的 m 和 n 的值。

我已经尝试了一些方法来捕获堆栈溢出,据我所知,c++ 没有我可以捕获的 stackoverflowexception。 try-catch block 不起作用。在下面的代码中,我使用 getrlimit() 来查找堆栈限制,在主 gStackRef 中创建一个地址位置。我调用 checkStack 递归地检查指向 gStackLimit 的局部变量指针。

有没有更好的方法来检查与递归方法相关的堆栈使用情况?我还要检查段错误吗?我会让你知道我在 unix 终端上运行。

#include <cstdlib>
#include <iostream>


#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/resource.h>

int getrlimit(int resource, struct rlimit *rlp);

using namespace std;

int * gStackRef;
int gStackLimit;

void checkStack(void);

int main(int argc, char *argv[])
{
        int temp = 0;
        gStackRef = &temp;
        rlimit myl;
        getrlimit(RLIMIT_STACK, &myl);
        gStackLimit = (myl.rlim_cur / 3 * 8 / 10) ;/* modified for segment fault */
        cout << gStackLimit << "\n";
        checkStack();
}

void checkStack()
{
        int temp = 0;
        int* pVariableHere = &temp;
        size_t stackUsage = gStackRef - pVariableHere;
        printf("Stack usage: %d / %d \n", stackUsage, gStackLimit);
        if(stackUsage > gStackLimit) return;
        else checkStack();
}

最佳答案

However anything higher than 3 or 4 does not return and freezes the terminal I'm using atm.

这就是阿克曼函数的意义所在。它的生长速度非常快。对于 m >= 4n >= 3,如果你递归地计算 A(m, n),我怀疑你的函数会在你死之前回来。

I have tried a few things to catch a stack overflow, for all i know c++ doesn't have a stackoverflowexception I can catch.

当然不是。进程超出堆栈空间。应该立即拆除。

Is there a better way of checking my stack usage in relation to recursive methods?

如果您必须使用递归,请通过创建您自己的堆栈数据结构来手动执行此操作,该结构分配在堆上而不是堆栈空间中。用它来跟踪你在递归中的位置。推送和弹出以及递归,而不是通过嵌套方法调用递归。

但最后,您无论如何都不应该使用递归来计算阿克曼。

关于c - 计算阿克曼时如何检查堆栈使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7573962/

相关文章:

.net - 堆栈溢出异常

c - 用于嵌入式系统的简约人类可读序列化格式解析器

Python 2.6 : os. rename() 或 os.renames() 报告 OSError 但文件名为 None

c - 为什么 `htons`和 `ntohs`都存在?

qt - QDir::count() 的实现是什么

c++ - SIGSEGV 在 C++ 循环中有一个非常大的数组

objective-c - 如何在 xcode 中将 NSMutableArray 对象转换为 const char

c++ - 如果我不给它一点额外的空间,弦就会发疯。谁能解释这里发生了什么?

c - 单链表似乎不起作用

assembly - Retq指令,从哪里返回