tags:

views:

209

answers:

2

Hi all,

I have a particular method that is occasionally crashing with an ArgumentException:

Destination array was not long enough. Check destIndex and length, and the array's lower bounds.:
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex)
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)

The code that is causing this crash looks something like this:

List<MyType> objects = new List<MyType>(100);
objects = FindObjects(someParam);
objects.AddRange(FindObjects(someOtherParam);

According to MSDN, List<>.AddRange() should automatically resize itself as needed:

If the new Count (the current Count plus the size of the collection) will be greater than Capacity, the capacity of the List<(Of <(T>)>) is increased by automatically reallocating the internal array to accommodate the new elements, and the existing elements are copied to the new array before the new elements are added.

Can someone think of a circumstance in which AddRange could throw this type of exception?


Edit:

In response to questions about the FindObjects() method. It basically looks something like this:

List<MyObject> retObjs = new List<MyObject>();

foreach(MyObject obj in objectList)
{
   if(someCondition)
       retObj.Add(obj);
}
+4  A: 

Are you trying to update the same list from multiple threads? That could cause problems... List<T> isn't safe for multiple writers.

Jon Skeet
The FindObjects() method itself instantiates a new List<> object, populates it and returns it. They are all single-threaded, so I don't think there are any chances for multiple threads to be working on the List.
Tim
@Tim: Then I can't see why it would happen. See if you can come up with a short but complete program which demonstrates the problem. If we can reproduce it, we should be able to fix it.
Jon Skeet
This is more or less what I was hoping to hear. I haven't been able to reproduce this problem, and it seems to me like it shouldn't ever happen. I just wanted to make sure I wasn't missing something before outright rejecting it as an issue.
Tim
The problem you have is that it definitely has happened, as you say you have a stack trace to prove it. I think a concurrency problem is most likely — you sure it's not a background task started by a UI button, for example, and the user is clicking it twice in quick succession?
Paul Ruane
+1  A: 
AllenG
Because that initialization is promptly discarded. It doesn't even *need* to be initialized in this way.
Adam Robinson