Does C++ limit recursion depth?

The limit in C++ is due to the maximum size of the stack. That’s typically less than the size of RAM by quite a few orders of magnitude, but is still pretty large. (Luckily, large things like string contents are typically held not on the stack itself.)

The stack limit is typically tunable at the OS level. (See the docs for the ulimit shell built-in if you’re on Unix.) The default on this machine (OSX) is 8 MB.

[EDIT] Of course, the size of the stack doesn’t entirely help by itself when it comes to working out how deep you can recurse. To know that, you have to compute the size of the activation record (or records) of the recursive function (also called a stack frame). The easiest way to do that (that I know of) is to use a disassembler (a feature of most debuggers) and to read out the size of the stack pointer adjustments at the start and end of every function. Which is messy. (You can work it out other ways – for example, computing the difference between pointers to variables in two calls – but they’re even nastier, especially for portable code. Reading the values out of the disassembly is easier IMO.)

Leave a Comment