In a Linux (or other Operating System) process when a subroutine is called, the memory for local variables comes from stack area of the process. Any dynamically allocated memory (using malloc, new, etc.) comes from the heap area of the process. During recursion local memory is allocated from stack area during function call and get cleared when the function execution is done.
Some more information can be obtained from the Call Stack wikipedia page.
The memory is being represented with lowest address being at the bottom and highest being at the top. Here are the steps to find the direction of stack growth in recursion using a quick C code. You can also download the code from github – process stack growth direction.
- Create a file main.c with the following code:
#include <stdio.h> void test_stack_growth_direction(recursion_depth) { int local_int1; printf("%p\n", &local_int1); if (recursion_depth < 10) { test_stack_growth_direction(recursion_depth + 1); } } main () { test_stack_growth_direction(0); }
- Compile the program using gcc and Run it. (This can be done on Mac or Linux).
gcc main.c ./a.out
- Here is the output on Mac (Mac OX X, Version 10.7.5, Processor 2.4 GHz Intel Code i5, Memory 4 GB, 1333 MHz, DDR3)
0x7fff6e9e19ac 0x7fff6f9e89a8 0x7fff6f9e8988 0x7fff6f9e8968 0x7fff6f9e8948 0x7fff6f9e8928 0x7fff6f9e8908 0x7fff6f9e88e8 0x7fff6f9e88c8 0x7fff6f9e88a8 0x7fff6f9e8888 0x7fff6f9e8868
- Here is the outcome on Ubuntu Linux (Cpu Intel(R) Xeon(R) CPU)
0x7ffffeec790c 0x7ffffeec78dc 0x7ffffeec78ac 0x7ffffeec787c 0x7ffffeec784c 0x7ffffeec781c 0x7ffffeec77ec 0x7ffffeec77bc 0x7ffffeec778c 0x7ffffeec775c 0x7ffffeec772c
The stack is growing downwards on these specific setups as memory addresses are reducing. This depends on the architecture of the system and may have different behavior for other architectures.