0

WRT my question: Code execution breaking during recursion

I don't want to increase the stack size for every application running in my account. Just one C++ executable.

What is the way to do it?

user5858
  • 1,082
  • 4
  • 39
  • 79
  • 2
    There is no need to increase stack size. You should eliminate unnecessary unbounded recursion instead. – user7860670 Jan 14 '18 at 12:30
  • Is that because the recursion goes too deep? You could just use tail recursion. Anyway if insistent on increasing stack size, you can pass something like `--stack, my_favourite_stack_size` as compiler args to g++. – George Jan 14 '18 at 12:33
  • 2
    I think [this](https://stackoverflow.com/questions/2275550/change-stack-size-for-a-c-application-in-linux-during-compilation-with-gnu-com) is the answer – user5858 Jan 14 '18 at 12:43
  • And move all big objects from the stack on the heap. I mean no huge local arrays in the recursive functions – Mihayl Jan 14 '18 at 13:15

1 Answers1

0

If you really need huge amount of stack space you can make use of Boost Context and temporarily allocate a custom amount of stack space. This works on a per-thread level so it might not answer your question. However, as already said in comments, you should probably improve your algorithm as increasing stack size is hardly ever needed.

#include <boost/context/fixedsize_stack.hpp>
#include <boost/context/continuation.hpp>

void recurse(int depth)
{
  std::cout << depth << std::endl;
  recurse(depth + 1);  // infinite recursion to test how far you can go
  std::cout << depth << std::endl;  // just to avoid tail recursion optimization.
}

int main(int argc, char* argv[])
{
  namespace ctx = boost::context;
  ctx::fixedsize_stack my_stack(100 * 1024 * 1024);  // adjust stack size for your needs
  ctx::continuation source =
    ctx::callcc(std::allocator_arg, my_stack, [](ctx::continuation&& sink) {
      // everything in here runs within a context with your custom stack.
      recurse(1);
      return std::move(sink);
    });

  // This starts the context and executes the lambda above.
  source = source.resume();

  return 0;
}

On Linux using GCC or Clang you could also replace fixedsize_stack with segmented_stack, which automatically grows until you run out of memory.

Boost Context is portable among most major platforms.

Stacker
  • 1,080
  • 14
  • 20