为什么stackalloc初始化的行为不一致?

时间:2018-12-30 22:23:04

标签: c#

以下代码用两个非零值初始化两个stackalloc数组。正确初始化数组A后,数组B仍然充满零,这与预期相反。

通过反汇编已编译的可执行文件,可以看到没有为数组B生成初始化代码。为什么?

(defn try [x]
 (print ("ASDASD")
))

(try 5) 

预期结果:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static unsafe void Main(string[] args)
        {
            double a1 = 1;
            double* A = stackalloc double[] { a1, 0, 0, a1, a1 }; // results in 1 0 0 1 1
            double* B = stackalloc double[] { a1, 0, 0, 0, 0}; // results in 0 0 0 0 0 

            for (int i = 0; i < 5; i++) Console.Write($"{A[i]} ");
            Console.WriteLine();
            for (int i = 0; i < 5; i++) Console.Write($"{B[i]} ");
        }
    }
}

实际结果:

1 0 0 1 1
1 0 0 0 0

2 个答案:

答案 0 :(得分:8)

感谢您在此处编写出色的repro!这似乎是issue 29092的副本。 repro有点不同,但是乍一看它遇到了同样的问题,还应该修复。此修复程序将包含在Dev16中。

答案 1 :(得分:2)

@JaredPar指出,这是一个需要修复的错误。

作为一个工作环境,我发现了两种避免此问题的方法。

一种是使用const variable

property NSNotificationCenter : class "NSNotificationCenter"
script AppDelegate
    property parent : class "NSObject"

    on myFunction()
        log "hey"
    end myFunction

    on applicationWillFinishLaunching_(aNotification)
        -- Insert code here to initialize your application before any files are opened
        set ws to workspaceClass's sharedWorkspace()
        set nc to ws's notificationCenter()
        tell nc to addObserver_selector_name_object_(me, "myFunction()", "Finished Downloading", missing value) --tried this
    end applicationWillFinishLaunching_
end script

const double a1 = 1;
double* A = stackalloc double[5] { a1, 0, 0, 0, a1 }; // output 1 0 0 0 1