runtime icon indicating copy to clipboard operation
runtime copied to clipboard

BitArray.CopyTo throws IndexOutOfRangeException under certain conditions

Open lilinus opened this issue 2 years ago • 2 comments

Description

If BitArray.CopyTo is invoked with:

  • destination array being an int[] (does not reproduce with bool[] nor byte[])
  • the destination array is too small
  • bit count in BitArray is not divisible by 32.

Throwing of ArgumentException is delegated to calling of Array.Copy. Although if the BitArray contains "extra bits", this check is not done for the last extra bits, so IndexOutOfRangeException can be thrown. The check is essentially of-by one under these circumstances.

Reproduction Steps

new BitArray(33).CopyTo(new int[1], 0);

Expected behavior

It should throw ArgumentException according to documentation

Actual behavior

It throws IndexOutOfRangeException

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

It's a bit of an edge case I think this is probably an oversight and not by design (ie. not incorrect documentation)

lilinus avatar Feb 23 '24 15:02 lilinus

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

Issue Details

Description

If BitArray.CopyTo is invoked with:

  • destination array being an int[] (does not reproduce with bool[] nor byte[])
  • the destination array is too small
  • bit count in BitArray is not divisible by 32.

Throwing of ArgumentException is delegated to calling of Array.Copy. Although if the BitArray contains "extra bits", this check is not done for the last extra bits, so IndexOutOfRangeException can be thrown. The check is essentially of-by one under these circumstances.

Reproduction Steps

new BitArray(33).CopyTo(new int[1], 0);

Expected behavior

It should throw ArgumentException according to documentation

Actual behavior

It throws IndexOutOfRangeException

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

It's a bit of an edge case I think this is probably an oversight and not by design (ie. not incorrect documentation)

Author: lilinus
Assignees: -
Labels:

area-System.Collections, untriaged

Milestone: -

ghost avatar Feb 26 '24 16:02 ghost

What do the CopyTo implementations in other collection types do in this case? I think this should inform whether we update the implementation or correct the documentation.

EDIT most common ICollection<T> implementations that I checked throw ArgumentException in this case so it's clear that this is a bug. I would support fixing this in the implementation.

eiriktsarpalis avatar Feb 26 '24 16:02 eiriktsarpalis