Skip to content

ArgumentOutOfRangeException when creating FrozenDictionary with very large strings #121673

@prozolic

Description

@prozolic

Description

When attempting to create a FrozenDictionary using the ToFrozenDictionary method on an array containing huge strings, anArgumentOutOfRangeExceptionis thrown.

Reproduction Steps

var minStr = "";
var maxStr = new string('a', Array.MaxLength / 4);
string[] keys = [minStr, maxStr];
var dict = keys.ToFrozenDictionary(x => x);

Expected behavior

FrozenDictionary should be created without throwing an error.

Actual behavior

ArgumentOutOfRangeException is thrown.

  • Error Message
System.ArgumentOutOfRangeException: 'minimumLength ('-1610612806') must be a non-negative value. (Parameter 'minimumLength')
Actual value was -1610612806.'
  • Statck trace
 System.ArgumentOutOfRangeException.ThrowNegative[T](T value, String paramName)
 System.ArgumentOutOfRangeException.ThrowIfNegative[T](T value, String paramName)
 System.Buffers.SharedArrayPool`1.Rent(Int32 minimumLength)
 System.Collections.Frozen.LengthBuckets.CreateLengthBucketsArrayIfAppropriate(String[] keys, IEqualityComparer`1 comparer, Int32 minLength, Int32 maxLength)
 System.Collections.Frozen.FrozenDictionary.CreateFromDictionary[TKey,TValue](Dictionary`2 source)
 System.Collections.Frozen.FrozenDictionary.ToFrozenDictionary[TKey,TValue](IEnumerable`1 source, IEqualityComparer`1 comparer)
 Program.<Main>$(String[] args)  ...

Regression?

No response

Known Workarounds

No response

Configuration

.NET 8+, Windows11( x64 )

Other information

The root cause is that the LengthBuckets.CreateLengthBucketsArrayIfAppropriate method causes an overflow when calculating the size of the array for buckets, resulting in creating an array using a negative value.
This is an edge case, but I have created a pull request(#121674).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions