What if we run out of stack space in C# or Python?

Supposing we are running a recursive algorithm on a very large data set that requires, say, 1 million recursive calls. Normally, one would solve such a large problem by converting recursion to a loop and a stack, but what if we do not want to or cannot rewrite the algorithm?

Python has the sys.setrecursionlimit(int) method to set the number of recursions. However, this is only part of the story; the program can still run our of stack space. C# does not have a equivalent method.

Fortunately, both C# and Python have option to set the stack space when creating a thread. In C#, there is an overloaded constructor for the Thread class that accepts a parameter for the stack size:

Thread t = new Thread(work, stackSize);

In Python, we can set the stack size by calling:

threading.stack_size(67108864)

We can then run our work under a new thread with increased stack size.

2 Comments

  • This may not be enough, its possible that the stack size required is larger than the memory addressable in your process. Then you will need to change your algorithm to partition the problem into manageable chunks

  • Don't recurse unless you absolutely positively have to.

Comments have been disabled for this content.