//int data[MAX_ITEMS];
int capacity;
int * data=nullptr;
data = new int[10];
capacity = 10;
void ListT::Insert(int key){
int * tmp = nullptr;
int i;
if (size == capacity) {
// allocate a new array of double the size
capacity *= 2;
tmp = new int[capacity];
// copy the data from the original array to the new array
for(i = 0; i < size; i++) {
tmp[i] = data[i];
}
// delete the old array.
delete [] data;
// change the pointer to point at the new item
data = tmp;
}
// just add it to the array.
data[size] = key;
size++;
}
valgrind ./listTest
==19867== ==19867== HEAP SUMMARY: ==19867== in use at exit: 400 bytes in 2 blocks ==19867== total heap usage: 8 allocs, 6 frees, 74,448 bytes allocated ==19867== ==19867== LEAK SUMMARY: ==19867== definitely lost: 400 bytes in 2 blocks ==19867== indirectly lost: 0 bytes in 0 blocks ==19867== possibly lost: 0 bytes in 0 blocks ==19867== still reachable: 0 bytes in 0 blocks ==19867== suppressed: 0 bytes in 0 blocks ==19867== Rerun with --leak-check=full to see details of leaked memory ==19867== ==19867== For lists of detected and suppressed errors, rerun with: -s ==19867== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
// in the header file
~ListT();
// in the implementation file.
ListT::~ListT() {
delete [] data;
data = nullptr;
capacity = 0;
}
// in ListT.h
ListT(const ListT & other);
// in ListT.cpp
ListT::ListT(const ListT & other) {
size_t i;
capacity = other.capacity;
size = other.size;
current = other.current;
data = new int[capacity];
for(i=0; i < size; i++) {
data[i] = other.data[i];
}
return;
}
a = b = c = d = e;
// in the header file
ListT & operator =(const ListT & other);
// in the implementation file
ListT & ListT::operator = (const ListT & other) {
size_t i;
if (this != & other) {
delete [] data;
capacity = other.capacity;
size = other.size;
current = other.current;
data = new int[capacity];
for(i=0; i< size; i++) {
data[i] = other.data[i];
}
}
return *this;
}