简体   繁体   中英

How can I increase the stack memory?

Duplicate of How to allow more memory and avoid stack overflow on lots of recursion?

I'm writing a branch and bound algorithm which has at least 10000 levels by a recursive function,but it doesn't work due to a stack overflow error. here is a simple instance of my program in C++:

void f(int k)
{
   if(k==10000) return;
   f(k+1);
} 

void main()
{
   f(1);
   return;
}

could anybody help?

This is a linker issue. You will need to tell the linker to increase the amount of memory allocated to the stack. This is different for different languages and compilers. It can be a command line parameter or it can be a configuration file or it can even be specified in the source code.

If you're on Linux (maybe Macs too?) you can use the ulimit command.

But you might want to look into optimizing your algorithm or looking into tail-recursion.

Any recursive algorithm can be rewritten as a non-recursive one using a list. This way you moved the problem from stack size to heap size, heaps being usually (much) larger than thread stacks. There are also stack size linker flags, depends on your compiler/linker and platform

或者您可以将递归重写为一个交互。

除了主要问题外,您还可以使用Valgrind及其工具Massif来配置堆栈消耗内存(默认情况下,Massif配置文件会堆积堆栈,如果打开了选项,则还可以配置堆栈)。

If you use _beginthreadex you can specify stack size. I believe the default is 1MB. You could spin off a new thread to do your work and specify whatever stack size you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM