Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are variables stored in memory in recursion?

I'm unsure about how variables are created and stored in memory during recursion. Below is an example taken from C Primer Plus:

#include <stdio.h>
void recursiontest(int); 

int main(){
    recursiontest(3); 
    return 0; 
}


void recursiontest(int n){
    printf("Level %d : %#x\n", n, &n); 
    if(n < 4)
        recursiontest(n + 1); 
    printf("LEVEL %d : %#x\n", n, &n);
    return;  
}

Which yields the output:

Level 3 : 0x3ce1f8bc

Level 4 : 0x3ce1f89c

LEVEL 4 : 0x3ce1f89c

LEVEL 3 : 0x3ce1f8bc

It appears as though the "n" variable local to the original function call is of an address sequentially later than that of the first (and only) recursive call. Why is that?

When I call a function, aren't its formal parameters declared and defined in terms of the actual argument passed to it? Wouldn't that mean that the integer n local to the first call is created before the second (recursive) call? How could the n of the second call have an address earlier than the first call?

like image 222
Theo Chronic Avatar asked Jul 12 '13 01:07

Theo Chronic


People also ask

How is recursion stored in memory?

Memory Allocation of Recursive Functions. A recursive function calls itself, so the memory for a called function is allocated on top of the memory allocated for calling the function. Remember, a different copy of local variables is created for each function call.

Does recursion save memory?

Recursion uses more memory. Because the function has to add to the stack with each recursive call and keep the values there until the call is finished, the memory allocation is greater than that of an iterative function.

What memory are variables stored?

Variables are usually stored in RAM. This is either on the heap (e.g. all global variables will usually go there) or on the stack (all variables declared within a method/function usually go there). Stack and Heap are both RAM, just different locations. Pointers have different rules.

Why more memory is consumed when using recursion?

Recursion consumes more memory because the recursive function is added to the stack with every recursive call. The values are stored there until the call completes.


1 Answers

This is because the local automatic variables created during the recursive function calls are stored on the stack, and the stack grows "down" from a higher to lower address on most platforms, including x86. Thus a function that is called later in the process will have variables with a "lower" address than variables stored from an earlier function call.

like image 89
Jason Avatar answered Sep 21 '22 13:09

Jason