dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.55k stars 4.54k forks source link

StringBuilder has incorrect (maximum) capacity handling #104310

Open cap5lut opened 2 days ago

cap5lut commented 2 days ago

Description

Everything regarding the (maximum) capacity of the StringBuilder revolves around int.MaxValue instead of Array.MaxLength, which is a smaller value. This can cause

System.OutOfMemoryException: 'Array dimensions exceeded supported range.'

because guard clauses mainly check for negative values/integer overflows and the default maximum capacity is set to int.MaxValue.

Reproduction Steps

  1. Create a new console project with the whole code being:
    new StringBuilder(int.MaxValue, int.MaxValue);
  2. Run

Expected behavior

An ArgumentOutOfRangeException will be thrown.

Actual behavior

System.OutOfMemoryException: 'Array dimensions exceeded supported range.' is thrown.

Regression?

I did not check prior to .NET 5, but since then this problem exists.

Known Workarounds

Setting the maximum capacity to Array.MaxLength manually.

Configuration

This is not platform/architecture specfic.

.NET SDK:
 Version:           8.0.302
 Commit:            ef14e02af8
 Workload version:  8.0.300-manifests.ca8b4b2d
 MSBuild version:   17.10.4+10fbfbf2e

Laufzeitumgebung:
 OS Name:     Windows
 OS Version:  10.0.19045
 OS Platform: Windows
 RID:         win-x64

Other information

dotnet-policy-service[bot] commented 2 days ago

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