3

I just had a unique error where a live site was throwing "Index was outside the bounds of the array" on login. I tracked the error down to an old "timing" file inherited from an old project. Here's the full class

public class TimingObject
{
    public DateTime timestamp { get; set; }
    public String call { get; set; }
    public TimeSpan duration { get; set; }

    // create a new timing object starting now
    public TimingObject()
    {
        timestamp = DateTime.Now;
    }

    public TimingObject(String call)
    {
        timestamp = DateTime.Now;
        this.call = call;
    }

    public void Stop()
    {
        List<TimingObject> timings;
        if (HttpContextManager.Current.Cache["PageTimings"] == null)
            timings = new List<TimingObject>();
        else
            timings = HttpContextManager.Current.Cache["PageTimings"] as List<TimingObject>;
        this.duration = (DateTime.Now - this.timestamp);
        timings.Add(this);
        HttpContextManager.Current.Cache["PageTimings"] = timings;
    }
}

The error was thrown by timings.Add(this). Why would Index was out of bounds be thrown when adding an item to a list?

Could this happen if the list is too big? And how big would it have to be exactly?

The code is redundant, and has been removed. But I'd really like to know why this happened.

roryok
  • 9,325
  • 17
  • 71
  • 138
  • 2
    Are you *sure* that's the line the error is on? – rory.ap Feb 28 '17 at 15:06
  • The maximum size of a `List` is `int32.MaxValue`, or around two billion one hundred forty seven million. However, because it is an array internally that grows as needed, if you wind up with a size over that value divided by two plus one, if it goes to add another item and needs to increase its size, it might try and add an index larger than it can handle. I'm not exactly sure on the logic there. – krillgar Feb 28 '17 at 15:07
  • Along with rory and David, I'd be curious to see what it is within the cache. Perhaps it is something else that gets cast as a list. – krillgar Feb 28 '17 at 15:09

1 Answers1

6

List<T> is not thread safe, and this code looks suspiciously like you would be fetching a shared instance of List<T> from multiple threads. I suspect you are adding to the list from two different threads simultaneously and throwing off the array that is making the List work under the covers.

Tim
  • 5,940
  • 1
  • 12
  • 18