我有一个递归算法,可能会深入研究,我不希望堆栈溢出。有没有一种方法可以将函数调用堆栈存储在堆而不是堆栈上?
答案 0 :(得分:2)
如果您真的想扩展堆栈空间,总会有callback
,它在类似posix的环境中可用,需要您在线程中完成工作,并可以分配任意数量的内容。它要求内存是可读写的(对于堆来说不是问题)并且需要某种程度的对齐,有关详细信息,请查阅手册页...
答案 1 :(得分:1)
如果您在函数中声明了很多要存储在堆栈中的变量,尤其是大型数组,则可以将变量移到堆中。
答案 2 :(得分:1)
我有一个递归算法,可能会深入研究 我不要堆栈溢出。有没有一种存储函数调用的方法 堆而不是堆上?
您探索过函子吗?
在下面,请注意
一个类的所有(常规)函数都包含隐藏的“ T * this”参数。
因此,每个函数都可以直接访问该类的任何数据属性。
也许“ Functor包装”可以减轻递归堆栈的负担,从而消除调用之间传递的许多参数。
简单示例:
class T934c_t // tail recursive, return string which contains step pattern,
{
stringstream ss; // data attributes ALL pass function-to-function
int64_t maxPtrnHgtWdth; // through the hidden this pointer.
public:
string operator()(int64_t max)
{
maxPtrnHgtWdth = max; // <<< save to functor data attributes
exec(); // <<< filled in during execution
return ss.str(); // return result of execution.
}
private:
void exec ()
{
ss << "\n\n\n string T934c_t()(int64_t): -->"
<< " void exec (int64_t) (" << maxPtrnHgtWdth
<< ")\n tail recursive, return string which contains step pattern, ";
execR (maxPtrnHgtWdth); // entry to recursive code
}
// 8..1
void execR (int64_t step) // recursive
{
if (0 >= step) return; // recursion termination
dotPndLine (step-1); // build each line with dots and pound signs
execR (step-1); // tail recursion
}
// 7..0
void dotPndLine (int64_t step) // single line
{
ss << "\n ";
dotR (step); // 7..0 dots
pndR (maxPtrnHgtWdth-step); // 1..8 pound sign
ss << ' ';
}
// 7..0
void dotR (int64_t dotCt) { // recursive
if (0 >= dotCt) return; // recursion termination
ss << '.'; // simple execution
dotR (dotCt-1); // tail recursion
}
// 1..8
void pndR (int64_t pndCt) { // recursive
if (0 >= pndCt) return; // recursion termination
ss << '#'; // simple
pndR (pndCt-1); // tail recursion
}
}; // class T934c_t