Reputation: 516
When does it cause a stackoverflow error in recursion in c++? What is the size of memory consumed while working with recursion? Is it 4 times the function invoked(4 being the size of pointer)? Does that mean there is a different pointer associated with each call?
Upvotes: 1
Views: 137
Reputation: 206577
Every platform has limits on the number of stack frames you can use in a program. When a recursive function does not meet its terminating criteria soon enough, it will lead to stack overflow.
In Microsoft Visual Studio compilers, you can specify the stack size using the compiler option /F
(There is also a linker option, /STACK
). Without this, the stack size is 1 MB. You can get more information at http://msdn.microsoft.com/en-us/library/tdkhxaks.aspx.
Each stack frame needs different amount of memory -- they are determined by the number and types of local variables, the type of the return value, the number and types of parameters. Hence, the number of stack frames you can use without causing stack overflow varies.
g++/gcc also have a way of specifying stack size using -Wl-stack_size
. You can find more on that subject at Change stack size for a C++ application in Linux during compilation with GNU compiler.
Upvotes: 2
Reputation: 500297
C++ as a language has no notion of a "stack" or "stack overflow".
The stack is an implementation detail. The amount consumed per call depends on your platform, your compiler, the actual code etc. As a rule of thumb, you can expect the return address and all of the function's arguments to be pushed onto the stack. Additionally, automatic variables usually live on the stack (but see below).
This is, however, a simplification: in some cases the compiler might be able to eliminate function calls altogether or turn them into jump instructions. Arguments are commonly passed in registers. Automatic variables can be optimized away or stored in registers. Etc etc.
If you want to know for sure, compile your code to assembly and carefully study the result. Alternatively, rig up some representative benchmarks and run them until the stack is exhausted.
Last but not least, the amount of stack available to an application is often configurable at the OS level.
Upvotes: 0