runtime icon indicating copy to clipboard operation
runtime copied to clipboard

`ArgumentOutOfRangeException` when creating FrozenDictionary or FrozenSet with very large strings

Open prozolic opened this issue 1 year ago • 4 comments

Description

When attempting to create a FrozenDictionary using the ToFrozenDictionary method on an array containing huge strings, anArgumentOutOfRangeExceptionis thrown. Under the same conditions, the ToFrozenSet method will also throw the same error.

Reproduction Steps

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

Expected behavior

FrozenDictionary or FrozenSet 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).

prozolic avatar Nov 16 '25 00:11 prozolic

Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.

dotnet-policy-service avatar Nov 16 '25 00:11 dotnet-policy-service

Appears to reproduce since the introduction of the type in .NET 8.

eiriktsarpalis avatar Nov 17 '25 15:11 eiriktsarpalis

The same error occurred in the ToFrozenSet method, so I added a note about that part.

prozolic avatar Nov 18 '25 13:11 prozolic

This issue has been closed as it was merged in #121674. Thank you for your support.

prozolic avatar Dec 27 '25 00:12 prozolic