Click to See Complete Forum and Search --> : recursion in C


JoseMourinho
February 27th, 2009, 10:09 AM
When a function is called during recursion what happens with the memory ? Is it true that memory is allocated in code segment for all recursive calls or memory is allocated just in the stack ?

If there is only one version of function in code segment what value has the return address in the memory allocated in the stack for all calls during the recursion ?

Peter_B
February 27th, 2009, 11:22 AM
Each function call in C is handled in the same way - it doesn't matter whether the call is recursive or not. The return address is put onto the stack, along with the local variables.

The wikipedia article explains all this better than I can: http://en.wikipedia.org/wiki/Call_stack

JoseMourinho
February 27th, 2009, 12:18 PM
During recursion how many copies of recursive function in code segment exists ?

Alex F
February 27th, 2009, 12:36 PM
Code segment contains one function instance. Stack contains number of function instances equal to current recursive call depth.
Code segment contains function executable code. Stack contains function return address, parameters and local variables.
As mentioned by Peter_B, functions are called by the same way, doesn't matter whether this is recursive call. To understand this better, maybe you need to learn some Assembly basics, this realy happens to write better in C and C++.
http://webster.cs.ucr.edu/AoA/DOS/index.html

JoseMourinho
February 27th, 2009, 12:51 PM
10x very much

If you tell me what is the content of the return address in the stack's areas of each recursive call (where return address points) i will be vary happy.

again 10x all

JoseMourinho
February 27th, 2009, 09:05 PM
"The address of the next statement to be executed after a function exits is called the return address for that particular function invocation. We need to keep track of this so that we know which statement to execute after exiting from a function."

So in function

int pow(int x , int n) {
if (n ==1 )
{return x;} else
{return x*pow(x,(n-1)) ;}
}


there will be n-1 areas in stack where the return address will have value the address of instruction in code segment (constant value) where is done x * result_of_call ?

Alex F
February 28th, 2009, 03:20 AM
Function return address points to the address of executable code, and not to the stack. Again, stack contains function return address, parameters and local variables, but not code itself.

JoseMourinho
February 28th, 2009, 03:25 AM
Yes , I know that. Return address will be loaded in IP (EIP) ...
10x