简体   繁体   中英

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

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",count );
  // It is not necessary to increment count since each function's
  //  variables are separate (so each count will be initialized one greater)
  recurse ( count + 1 );
}

this program halt when count is equal 4716 ! so the limit is just 4716 !! I'm a little bit confused !! why the program stops exeuction when the count is equal to 4716 !! PS: Executed under Visual studio 2010. thanks

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.

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

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.

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