views:

448

answers:

6

Duplicate of http://stackoverflow.com/questions/743545/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?

+4  A: 

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.

sybreon
A: 

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

Remus Rusanu
A: 

or you could rewrite the recursion into an interation.

Mladen Prajdic
+2  A: 

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.

swampsjohn
A: 

Besides your main question, you could use Valgrind and its tool Massif, to profile your stack consumption memory (Massif profiles heap by default, but also can profile stack, if an option is turned on).

A: 

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.

Angus