[Mono-dev] Crazy StackAlloc

Jambunathan K kjambunathan.devel at gmail.com
Thu May 7 07:52:11 EDT 2009


I was little out of my mind and I tried crazy stackalloc both on Mono
and Windows XP.

The intention was to find out the max stack size available. There are
a couple of surprises both Windows and Mono. Both the runtimes was
behaving differently from my expectations.

On Windows, there is __no__ StackOverflowException as one would expect.
There was only a NullReferenceException.

On Mono, there is a StackOverflowException with the runtime getting
starved stack space.

My mono version is 2.4. My .NET - 1.1 environment is atleast 4 years old.

Please don't question the reasonableness of stackalloc size. What
interests me is the runtime behaviour.

You might have to play around with 'size' to get the runtime to behave crazily.

Output on Windows is down below. Audience can check out the behaviour
on Mono for
themselves.

C:\Documents and Settings\Owner>type StackAllocCrazy.cs
using System;

class T
{

        public unsafe static void Main ()
        {
        int size = 1 * 1024 * 1024 * 1024;

        while (size != 0) {
                Console.WriteLine ("Trying " + size + " bytes ...");

                try {
                        long *buf = stackalloc long[size];

                        for (int i = 0; i < size; ++i)
                                buf[i] = 0;

                } catch (Exception e) {
                        Console.WriteLine ("Caught " + e);
                        size /= 2;
                        continue;
                }

                Console.WriteLine ("Can stackalloc " + size + " longs");
                break;
        }
        }
}

C:\Documents and Settings\Owner>csc /unsafe StackAllocCrazy.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.


C:\Documents and Settings\Owner>StackAllocCrazy.exe
Trying 1073741824 bytes ...
Caught System.NullReferenceException: Object reference not set to an instance of
 an object.
   at T.Main()
Trying 536870912 bytes ...
Caught System.NullReferenceException: Object reference not set to an instance of
 an object.
   at T.Main()
Trying 268435456 bytes ...


Regards,
Jambunathan K.


More information about the Mono-devel-list mailing list