Есть ли способ предотвратить нарушение прав записи при вставке элементов в заднюю часть массива Dynami c? - PullRequest
0 голосов
/ 26 марта 2020

Я хочу использовать функцию insertBack() для добавления элементов в конец массива; но я получаю сообщение об ошибке при попытке сделать это:

Необработанное исключение: нарушение прав доступа на запись. this-> arr был 0x1110116.

Я не уверен, что я делаю неправильно; должность и предпосылки моего профессора просто сбивают меня с толку. Я также не знаю, как используется метод allocate и является ли мой способ удвоения емкости правильным.

Класс контейнера:

#include <iostream>

template<typename T>
class container
{
    template <typename T2>
    friend std::ostream& operator<<(std::ostream& out, const container<T2> &cobj);
    // Postcondition: contents of the container object cobj is displayed
public:
    container();
    // Postcondition: an empty container object is created with data members 
    // arr set to NULL, n set to -1 and Capacity set to 0
    ~container();
    // Destructor; required as one of the Big-3 (or Big(5) because of the 
    // presence of a pointer data member. Default version results in 
    // memory leak!
    // Postcondition: dynamic memory pointed to by arr has been release back to 
    // the “heap” and arr set to NULL or nullptr
    // In order to see the action, message "destructor called and 
    // dynamic memory released!" is displayed
    bool isEmpty() const;
    // Postcondition: returns true is nothing is stored; returns false otherwise
    bool isFull() const;
    // Postcondition: returns true if arr array is filled to capacity; 
    // returns false otherwise
    int size() const;
    // Postcondition: returns the size or the number of elements (values) 
    // currently stored in the container
    int capacity() const;
    // Postcondition: returns the current storage capacity of the container
    bool insertBack(const T& val);
    // Postcondition: if container is not full, newVal is inserted at the 
    // end of the array; 
    // otherwise, double the current capacity followed by the insertion
private:
    void allocate(T* &temp);
    // Postcondition: if Capacity = 0, allocate a single location; 
    // otherwise the current capacity is doubled
    T *arr;
    int Capacity;   // Note: Capital 'C' as capacity is used as a function name
    int n;          // size or actual # of values currently stored in the container; 
                    // n <= SIZE
};

Определения функций / Код:

template<typename T2>
std::ostream& operator<<(std::ostream& out, const container<T2> &cobj)
{
    std::cout << "Currently it contains " << cobj.size() << " value(s)" << std::endl
        << "Container storage capacity = " << cobj.capacity() << std::endl
        << "The contents of the container:" << std::endl;

    if (cobj.isEmpty())
    {
        std::cout << "*** Container is currently empty!" << std::endl;
    }
    else
    {
        for (int i=0; i<cobj.size(); ++i)
        {
            std::cout << cobj.arr[i];
        }
    }

    return out;
}

template<typename T>
container<T>::container()
{
    arr = nullptr;
    Capacity = 0;
    n = 0;
}

template<typename T>
container<T>::~container()
{
    delete arr;
    arr = nullptr;
    std::cout << "Destructor called! (this line is normally not displayed)" 
              << std::endl;
}

template<typename T>
bool container<T>::isEmpty() const
{
    return n==0;
}

template<typename T>
bool container<T>::isFull() const
{
    return n==Capacity;
}

template<typename T>
int container<T>::capacity() const
{
    return Capacity;
}

template<typename T>
int container<T>::size() const
{
    return n;
}

template<typename T>
bool container<T>::insertBack(const T& val)
{
    if (size()>=Capacity)
    {
        Capacity = Capacity*2;
        n++;
        arr[n] = val;
        return true;
    }
    else
    {
        return false;
    }
}

template<typename T>
void container<T>::allocate(T* &temp)
{
    if (Capacity==0)
    {
        temp = new T;
    }
    else
    {
        return Capacity*2;
    }
}

int main()
{
    container<int> a1;
    std::cout << a1 << std::endl; 
    std::cout << "Currently, the container object contains 0 element(s) or 0 value(s)" 
              << std::endl;

    std::cout << "\nWe now insert 3 values at the back of the array, one at a time:" 
              << std::endl;

    const int num = 3;
    for (int i=0, c=0; i<=num; ++i, c+=10)
    {
        a1.insertBack(c);
    }

    std::cout << a1;
}

1 Ответ

2 голосов
/ 26 марта 2020

Когда вы используете insertback() и size() >= Capacity ,, ваш массив на самом деле не расширяется. Вы просто удваиваете переменную с именем Capacity, но сам массив фактически не удваивается.

Вы можете попробовать этот код для удвоения массива следующим образом:

T* old_array = arr; arr = new T[Capacity<<=1];  //double array
for(int i=0;i<n;++i) arr[i]=old_array[i]   //copy you can use memcpy instead for loop
delete [] old_array;    //free space

Есть некоторые другие ошибки, найденные в вашем коде:

  1. Деструктор

    Вы должны использовать delete []arr вместо delete arr.

    delete освобождает память, для которой выделен одиночный указатель объекта для нового.

    delete [] освобождает память, что недавно выделенный массив объектов указатель указывает на.

    И не забудьте проверить, что arr равен nullptr перед использованием delete.

  2. insertback

    Использовать arr[n]=val; до n++;.

  3. void container<T>::allocate(T* &temp)

    Тип возврата allocate() равен void . Поэтому вы не можете return Capacity*2;.

Совет:

Я рекомендую установить емкость по умолчанию для Container. Поэтому, если емкость не указана, запросите пространство по умолчанию вместо установки емкости на ноль.

...