Why does stackalloc initialization have inconsistent behavior?

  • A+
Category:Languages

The following code initializes two stackalloc arrays with non-zero values. While array A is properly initialized, array B remains filled with zeroes, contrary to what is expected.

By disassembling the compiled executable, one can see that no initialization code is generated for array B. Why is that?

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]} ");         }     } } 

Expected results:

1 0 0 1 1

1 0 0 0 0

Actual results:

1 0 0 1 1

0 0 0 0 0

 


Thanks for writing up a nice repro here! This appears to be a duplicate of issue 29092. The repro is a bit different but at a quick glance it's hitting the same problem and should also be fixed. The fix for this will be included in Dev16.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: