How to deliberately throw a StackOverflowException without using recursion?

I was told that each method has a 1 mb stack. Therefore, I suggested that initializing 256 integer values ​​with a single method will throw a StackOverflowException. I tried this in code, but there was no exception.

So, how to deliberately throw a StackOverflowException without using recursion?

+7
c # stack-overflow recursion
Oct 10 '11 at 8:25
source share
4 answers

I will add another way :-)

unsafe struct FixedBufferExample { public fixed byte Buffer[128 * 1024]; // This is a fixed buffer. } 

Now this structure is 128kb :-) If you declare a local variable (of a method that does not use yield or async) of type FixedBufferExample , it should use the 128kb stack. You can quickly use your stack.

+5
Oct 10 2018-11-11T00:
source share

using

 throw new StackOverflowException (); 
+19
Oct 10 '11 at 8:27
source share

stackalloc is probably the easiest way (assuming you want the runtime to choose the error, not you yourself):

  unsafe void Boom() { int* data = stackalloc int[512 * 1024]; // 2MB } 
+7
Oct 10 '11 at 8:29
source share

Call your property inside your property (this is recursion, but it is so common that I should have mentioned this):

 int MyProperty { set { MyProperty = value; } } 
-2
Oct 10 2018-11-10T00:
source share



All Articles