I have this code for managing dynamic collection List, which is mostly inspired with .NET System.List collection, but this is written in normal C++.
void List<T>::Insert(int index, T item)
{
if(index > GetLength() && index >= 0)
throw new StandartException("Index was out of array range");
if(GetLength()==length)
{
T * newl = new T[length + 4];
this->CopyTo(newl);
delete[] this->items;
this->items = newl;
length += 4;
}
T * store = new T[length];
CopyTo(store, index);
store[index] = item;
CopyTo((store + index + 1), index, GetLength() - index);
used++;
delete[] items;
items = store;
}
template <typename T>
void List<T>::CopyTo(T * destination, int start, int count)
{
for(int i = start, c = 0;i < GetLength() && c < count;i++, c++)
*(destination + i) = items[i];
}
So there is method Insert, which has to insert item on specified index in array.
For first, I’m checking if is index specified between 0 and Length + 1 (because I need to have a option to add item on the ond of collection). Then I’m testing if it is not end of allocated array (GetLength() = gets number of elements in array, length = number of allocated space for elements). If it is, I’m allocating new space for array, copying actual elements, freeing old storage and setting pointer to new address.
After that I’m allocating new space again. I’m copying actual elements from zero to index – 1, setting item which has to be inserted on it’s position and copying other old elements to thier indexes (their previous index + 1). On the end I’m freeing old space and adding new.
ERROR: I started debugging. Everything was normal, I’ve run Insert for first without problem, but on first deletion (delete[] this->items; in if block) I’ve received this error:

Does anybody know why am I getting this and how can I repair it? I think that I haven’t gone throught array range anywhere.
Please help.
Your problem is this line:
You insert an item, but don’t allocate an array that is any larger than before. When you go to
CopyTothe new array, you overflow the array.