how to deliberately trigger a StackOverflowException without using recursion?

I was told that every method has a stack the size of 1mb. So I assumed that initializing 256 integer values in one method will cause a StackOverflowException. I tried that in code, but no exception was thrown.

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


I'll add another method :-)

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 doesn't use yield or async) of type FixedBufferExample it should use 128kb of stack. You can use up your stack quite quickly.


使用

throw new StackOverflowException ();

stackalloc可能是最简单的方法(假设你希望运行时抛出错误,而不是你自己):

    unsafe void Boom()
    {
        int* data = stackalloc int[512 * 1024]; // 2MB
    }
链接地址: http://www.djcxy.com/p/80754.html

上一篇: 这个的目的是什么?

下一篇: 如何在不使用递归的情况下故意触发StackOverflowException?