Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does stackalloc initialization have inconsistent behavior?

Tags:

c#

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
like image 938
Igor Gribanov Avatar asked Dec 30 '18 22:12

Igor Gribanov


2 Answers

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.

like image 101
JaredPar Avatar answered Nov 04 '22 17:11

JaredPar


As it is stated by @JaredPar, It is a bug that is needed to be fixed.

As a workarround, I found two ways to avoid this problem.

one is to use const varible

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

or

double a1 = 1;
double a0 = 0;
double* A = stackalloc double[5] { a1, a0, a0, a0, a1 }; // output 1 0 0 0 1
like image 2
Derviş Kayımbaşıoğlu Avatar answered Nov 04 '22 18:11

Derviş Kayımbaşıoğlu