Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursion and memory

I have a program that passes in huge amounts of data, say 1000 variables, through recursion. The recursion would run to atleast 50 or 60 times. What I'm worried about is, is there a possibility of data getting over- written on the memory locations because there isn't much space, or if the case were that there is no memory, I would get some exception that the program memory has run out (I received no such error)?

Is there a possibility of getting a wrong solution because the program does not have any more memory and is over-writing on existing locations?

like image 938
Floose Avatar asked Nov 24 '12 19:11

Floose


People also ask

Does recursion use 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.

Does recursion use less memory?

Explanation: Recursion uses more memory compared to iteration because every time the recursive function is called, the function call is stored in stack.

Why recursion is memory intensive?

Recursion is memory-intensive because: Previous function calls are still open when the function calls itself and the activation records of these previous calls still occupy space on the call stack.

Does recursion use more memory than iteration?

Recursion is usually slower than iteration due to the overhead of maintaining the stack. Recursion uses more memory than iteration. Recursion makes the code smaller.


1 Answers

There are two storage areas involved: the stack and the heap. The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. The Hotspot documentation says that on Linux 64-bit each thread has a stack of 1024kB by default. The heap can be made arbitrary big, and today it's in the order of GB.

A recursive method uses both the stack and the heap. Which one you run out of first depends on the implementation. As an example, consider a method which needs thousands of integers: if they are declared as local variables, ie:

public void stackOverflow() {
  int a_1;
  int a_2;
  int a_3;
  // ...
  int a_10_000_000;
}

your program will crask with a StackOverflowError. On the other hand, if you organize your integers in an array, like:

public void outOfMemory() {
  int[] integers = new int[10 * 1000 * 1000];
} 

the heap will be filled soon, and the program will end with an OutOfMemoryError. In neither case the memory is corrupted or data overridden. However, in both cases the code is wrong and must be fixed somehow - but to tell you how we'd need to know more about your program.

like image 186
Raffaele Avatar answered Oct 03 '22 10:10

Raffaele