日期:2014-05-20  浏览次数:20811 次

c#中的堆栈的内存分配
c#中在堆栈中内存分配是向下填充的,即由高内存地址向低内存地址分配,为了证明这个问题,写代码如下:
class   Program
        {
                static   unsafe   void   Main(string[]   args)
                {
                        int   x   =   1;
                        int   y   =   2;
                        double   z   =   3.6;
                        Console.WriteLine( "Address   of   x   "   +   (uint)&x);
                        Console.WriteLine( "Address   of   y   "   +   (long)(&y));
                        Console.WriteLine( "Address   of   z   "   +   (long)(&z));

                }
        }
显示结果是:
Address   of   x   1242224
Address   of   y   1242220
Address   of   z   1242212
说明内存由高到低分配。

如果代码如下(即删掉变量z的声明):
class   Program
        {
                static   unsafe   void   Main(string[]   args)
                {
                        int   x   =   1;
                        int   y   =   2;
                        Console.WriteLine( "Address   of   x   "   +   (uint)&x);
                        Console.WriteLine( "Address   of   y   "   +   (long)(&y));
                }
        }
显示结果是:
Address   of   x   1242228
Address   of   y   1242232
内存好像是由低到高分配。

再次重写代码如下(即改变变量y的类型):
class   Program
        {
                static   unsafe   void   Main(string[]   args)
                {
                        int   x   =   1;
                        double   y   =   2.2;
                        double   z   =   3.6;
                        Console.WriteLine( "Address   of   x   "   +   (uint)&x);
                        Console.WriteLine( "Address   of   y   "   +   (long)(&y));
                        Console.WriteLine( "Address   of   z   "   +   (long)(&z));