Skip to content

Array might not be zero-initialized #79882

Closed
@threbejk

Description

@threbejk

Description

We have found, that elements of an array might not be always initialized to the default value. For example, after calling new double[size], some elements might be nonzero. We have started noticing this problem after upgrading to .net7. It seems, that this happens especially when the GC heap size limit is set. (Initially, we observed this with 8 GB limit.)

Reproduction Steps

Run this C# program:

using System;

var rand = new Random();
try
{
    for (int k = 0; k < 1_000_000; k++)
    {
        Test(k);
    }
    Console.Write("Succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Failed");
    Console.WriteLine(ex.Message);    
}

void Test(int iteration)
{
    int size = (int)Math.Pow(10, 5 + rand.NextDouble() * (1 + rand.NextDouble()));

    var m = new double[size];
    for (int i = 0; i < size; i++)
        if (m[i] != 0)
            throw new Exception(m[i].ToString() + "; " + i + "/" + size + "; iteration " + iteration.ToString());

    for (int i = 0; i < size; i++)
        m[i] = 21;
}

With GC HeapHardLimit set to 1 GB

{
  "configProperties": {
    "System.GC.HeapHardLimit": 1000000000
  }
}

Expected behavior

We expect that Exception is not thrown, because elements of the array should be initialized to zero.

Actual behavior

With high probability, Exception is thrown, because an element is not zero.

Regression?

We haven't noticed this issue in .net6.

Known Workarounds

No response

Configuration

.net version 7.0.100
MS Windows 10 Pro, x64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions