#include <cstdlib>
#include <cassert>
#include <cstring>
#include <new>
template <typename T>
class ArrayList
{
private:
unsigned capacity;
unsigned size;
T* array;
public:
ArrayList(unsigned initCapacity);
~ArrayList();
void add(const T& newElement);
void add(unsigned index, const T& newElement);
T remove(unsigned index);
private:
void grow();
};
template <typename T>
ArrayList<T>::ArrayList(unsigned initCapacity = 10)
{
if (initCapacity == 0)
throw"ArrayList capacity must be greater than 0!";
size = 0;
capacity = initCapacity;
array = new (std::nothrow) T[initCapacity];
assert(array != 0);
}
template <typename T>
ArrayList<T>::~ArrayList()
{
delete [] array;
}
template <typename T>
void ArrayList<T>::add(const T& newElement)
{
assert(capacity > size);
// insert, and resize if necessary
array[size++] = newElement;
if (size == capacity)
grow();
}
template <typename T>
void ArrayList<T>::add(unsigned index, const T& newElement)
{
assert(capacity > size);
if (index > size)
throw"Addition index cannot be greater than array size!";
if (index == size)
add(newElement);
else
{
// shift
for (int i = size - 1; i >= static_cast<int>(index); --i)
array[i + 1] = array[i];
// insert
array[index] = newElement;
// resize if necessary
if (++size == capacity)
grow();
}
}
template <typename T>
T ArrayList<T>::remove(unsigned index = 0)
{
if (index >= size)
throw"Removal index cannot be greater than array size minus 1!";
T removed = array[index];
if (index != size - 1)
for (int i = index; i <= static_cast<int>(size) - 2; ++i)
array[i] = array[i + 1];
--size;
return removed;
}
template <typename T>
void ArrayList<T>::grow()
{
capacity *= 2;
T* newArray = new (std::nothrow) T[capacity];
assert(newArray != 0);
for (int i = 0; i < static_cast<int>(size); ++i)
newArray[i] = array[i];
delete [] array;
array = newArray;
}
I have driver code that stresses everything here. A memory checker surrounding this driver program claims that every time delete is called from the destructor or from grow(), I am attempting to free unallocated memory. This makes no sense to me.
is your ArrayList ever being used without using the constructor you defined?
I.E.
1 2
ArrayList al;
al = ArrayList(14);
This would cause the unallocated memory error to occur.
I think it matters (can't be positive without testing it), but try putting your initializer in the ArrayList constructor's declaration rather than definition...