Limit recursive calls in C++ (about 5000)?

前端 未结 3 613
独厮守ぢ
独厮守ぢ 2021-01-05 23:03

In order to know the limit of the recursive calls in C++ i tried this function !

void recurse ( int count ) // Each call gets its own count
{
printf(\"%d\\n\         


        
相关标签:
3条回答
  • 2021-01-05 23:44

    The stack size is dependent on your environment.

    In *NIX for instance, you can modify the stack size in the environment, then run your program and the result will be different.

    In Windows, you can change it this way (source):

    $ editbin /STACK:reserve[,commit] program.exe
    
    0 讨论(0)
  • 2021-01-05 23:55

    The limit of recursive calls depends on the size of the stack. The C++ language is not limiting this (from memory, there is a lower limit of how many function calls a standards conforming compiler will need to support, and it's a pretty small value).

    And yes, recursing "infinitely" will stop at some point or another. I'm not entirely sure what else you expect.

    It is worth noting that designing software to do "boundless" recursion (or recursion that runs in to the hundreds or thousands) is a very bad idea. There is no (standard) way to find out the limit of the stack, and you can't recover from a stack overflow crash.

    You will also find that if you add an array or some other data structure [and use it, so it doesn't get optimized out], the recursion limit goes lower, because each stack-frame uses more space on the stack.

    Edit: I actually would expect a higher limit, I suspect you are compiling your code in debug mode. If you compile it in release mode, I expect you get several thousand more, possibly even endless, because the compiler converts your tail-recursion into a loop.

    0 讨论(0)
  • 2021-01-06 00:01

    You've probably run out of stack space.

    Every time you call the recursive function, it needs to push a return address on the stack so it knows where to return to after the function call.

    It crashes at 4716 because it just happens to run out of stack space after about 4716 iterations.

    0 讨论(0)
提交回复
热议问题