9

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?

3
  • 7
    256 * 4 bytes = 1kb, not 1mb Commented Oct 10, 2011 at 8:27
  • 3
    256 integers is = 256 * 4 bytes = 1024 bytes = 1 kb, not 1 MB. Therefor, you would need 256000 integers. And I wouldn't even try to write a code with 256000 declarations. (edit: and Marc Gravells is always faster) :) Commented Oct 10, 2011 at 8:28
  • 1
    It would be pretty bad if you could only use 256 * 4 bytes of memory in a single method... On the other hand, it would probably help keep methods small! :-) Commented Oct 10, 2011 at 8:30

3 Answers 3

18

use

throw new StackOverflowException ();
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Always use the simplest approach that gets the result you are after? :)
8

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
    }

1 Comment

is there any difference if used on 64 Bit system ? Is the stack bigger ?
6

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.

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.