0

I'm trying to make an ArrayList, an ADT object that uses dynamically allocated arrays to store data. It's supposed to mimic the vector class in that all I want the object to do is:

  1. store data in a dynamically array
  2. I want to define a default constructor (but I don't want to define any of the big three if I don't need to, and I don't think I need to)
  3. have a working size function that returns the current size of the object's array, i.e the size of the list
  4. an at() function
  5. an insert(index, value) function
  6. a remove(index) function

I keep getting leakage errors tho :( I have attached my code for my header file, and a cpp file where I define my member functions. Does anyone think they can take a quick look at my code and tell me what I'm doing wrong?

header file:

#ifndef ARRAYLIST_H
#define ARRAYLIST_H 

#include <cstdlib>

// declare class here
class ArrayList{

  private:
    int listSize;
    int* arr;

  public:
    ArrayList();
    int size() const;
    int at(int index) const;
    void insert(int index, int value);
    void remove(int index);


};

#endif  // ARRAYLIST_H

#include <stdexcept> // 

#include "ArrayList.h"

// define class methods here
ArrayList::ArrayList() {

  listSize = 0;
  arr = new int[listSize];
  
}

int ArrayList::size() const{
  return listSize;
}

int ArrayList::at(int index) const{

  return arr[index];  

}

void ArrayList::insert(int index, int value) {

  // make a tempArr
  // make listSize the listSize+1
  // iterate through new tempArr and make it the same as arr until index is reached. 
    // at index, do tempArr[index] = value;
  listSize++;
  int* tempArr = new int[listSize];

  for(int i = 0; i < listSize; i++){

    if(i < index){
      tempArr[i] = arr[i];
    }
    else if(i == index){
      tempArr[index] = value;
    }
    else{
      tempArr[i] = arr[i - 1];
    }

    delete [] arr;

    arr = tempArr;

  }
}

void ArrayList::remove(int index){

  listSize--;
  int* tempArr = new int[listSize]; // making a temporary dynamically allocated arr

  for(int i = 0; i < listSize; i++){

    if(i == index){ // skipping copying this element
      continue;
    }

    tempArr[i] = arr[i];

    delete [] arr;

    arr = tempArr;

  }

}
cigien
  • 57,834
  • 11
  • 73
  • 112
Ayo
  • 19
  • 5
  • 4
    "I don't want to define any of the big three if I don't need to, and I don't think I need to" - You're utterly wrong about that. You allocate memory in your default constructor. Where exactly do you think it will get freed? – Sebastian Redl Nov 27 '21 at 22:33
  • 2
    You'd better move those `delete [] arr; arr = tempArr;` *outside* the loops. – Bob__ Nov 27 '21 at 22:49
  • 1
    And your `ArrayList::remove` method is completely broken. Off-by-one past the skipped element, and double-free in a loop. – Ext3h Nov 27 '21 at 22:52

0 Answers0