Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Cui Pengfei 崔鹏飞 Avatar asked Oct 10 '11 08:10

Cui Pengfei 崔鹏飞


3 Answers

use

throw new StackOverflowException ();
like image 56
Yahia Avatar answered Nov 08 '22 13:11

Yahia


stackalloc is probably the easiest way (assuming you want the runtime to throw the error, rather than yourself):

    unsafe void Boom()
    {
        int* data = stackalloc int[512 * 1024]; // 2MB
    }
like image 28
Marc Gravell Avatar answered Nov 08 '22 11:11

Marc Gravell


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.

like image 41
xanatos Avatar answered Nov 08 '22 11:11

xanatos