1

Sample Code :

Static void main(string[] args) { Class1 c1 = new Class1(); }

Class1 { Class1() { Class2 c2 = new Class2(); } }

Class2 { Class2() { Class1 c1 = new Class1(); } }

The above code throws StackOverFlowException. Here we are creating Class1 & Class2 objects recursively. Objects are stored in Heap, then why it is not throwing HeapOversizedException or someotherException Related to Heap?

3
  • 5
    Because you are not running out of heap (memory), you are blowing the stack with recursion. Commented Oct 11, 2013 at 9:42
  • 4
    Additionally, there is a "heap oversized exception". It's called OutOfMemoryException. Commented Oct 11, 2013 at 9:45
  • That will be defined as OutOfMemoryException this is Stack which refers to Thread's Execution Stack Commented Oct 11, 2013 at 9:45

2 Answers 2

8

Infinite recursion always causes StackOverflowException. This is not because of object allocations but because the call to a method must remember the address of the caller on the stack and doing it infintely overflows the stack.

Wikipedia has a quite formal description of that process.

Sign up to request clarification or add additional context in comments.

1 Comment

To add, every time that you call a function (and in this case, the constructor), the stack has to remember where to return to (after the function is called). It has a limited number of places to store this return information.
3

StackOverflowException - stack will be used to store current address and jump to function code to execute. Then it will be released or popped when function returns. Since your call never going to end or return, continuously stack has been filled with address and got it filled.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.