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?
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:
your program will crask with a
StackOverflowError. On the other hand, if you organize your integers in an array, like: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.