Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relate Array.MaxLength to int.MaxValue #10714

Closed

Conversation

GrabYourPitchforks
Copy link
Member

Summary

Document the guarantee that Array.MaxLength < int.MaxValue. Typical for loops are subject to failure without this guarantee. Example:

for (int i = 0; i < someArray.Length; i++)
{
    _ = someArray[i]; // if MaxLength = int.MaxValue, 'i' could overflow to int.MinValue, resulting in illegal access
}

Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-runtime

@tannergooding
Copy link
Member

@GrabYourPitchforks, the code sample you gave isn't prone to the error.

Given:

for (int i = 0; i < someArray.Length; i++)
{
    _ = someArray[i]; // if MaxLength = int.MaxValue, 'i' could overflow to int.MinValue, resulting in illegal access
}

Then even if someArray.Length was int.MaxValue (such as it could be for Span<T>) then i itself can never be int.MaxValue. At worst you have i = 0; i = 1; ...; i = 2147483646 all of which are valid indices. Then i++ on the next iteration makes it i = 2147483647, the comparison i < someArray.Length occurs which evaluates as 2147483647 < 2147483647 which is always false, and the loop exits.

This is only really an issue with i <= someArray.Length, where it can be prone to an infinite loop, but would still fail on access due to the bounds check which is done strictly as i >= 0 && i < Length

@tannergooding
Copy link
Member

tannergooding commented Nov 26, 2024

Which is to say, in safe code such as the above, there is no risk for an illegal access. There is only risk of an infinite loop and prevention of an access resulting in IndexOutOfRangeException (the access is not actually attempted, as that would result in AccessViolationException or data that shouldn’t be returned getting returned if the location wasn’t protected)

Copy link

Learn Build status updates of commit 5139c88:

✅ Validation status: passed

File Status Preview URL Details
xml/System/Array.xml ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

@GrabYourPitchforks GrabYourPitchforks marked this pull request as draft November 26, 2024 22:03
@GrabYourPitchforks
Copy link
Member Author

GrabYourPitchforks commented Nov 26, 2024

Thanks @tannergooding for the check! I'll correct the wording and resubmit after researching a few things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants