功能删除在第二次激活时不工作

时间:2016-11-17 20:05:14

标签: c++ dynamic-memory-allocation

我有一个包含删除功能的功能:

void Vector::reserve(int n){
    //if there is a need to increase the size of the vector
    if (n > _size){
        int* tampArr;
        //check what the new size of the array should be
        _capacity = n + (n - _capacity) % _resizeFactor;
        tampArr = new int[_capacity];
        //put in the new array the element i have in the curr array
        for (int i = 0; i < _size; i++){
            tampArr[i] = _elements[i];
        }
        delete[] _elements;
        _elements = NULL;//this 
        //put the new array in _element
        _elements = new int[n];
        for (int i = 0; i < _size; i++){
            _elements[i] = tampArr[i];
        }
        delete[] tampArr;
    }
}

类字段是:

private:
    //Fields
    int* _elements;
    int _capacity; //Total memory allocated
    int _size; //Size of vector to access
    int _resizeFactor; // how many cells to add when need to reallocate

由于某种原因我第一次使用该功能它没有显示任何错误并且工作完美但在第二次停止在该行:“delete [] _elements;”它停了 另外,当我运行这个函数时,它会在对象的末尾停止:

Vector::~Vector(){
    delete[] _elements;
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:-3)

在删除之前,您不会检查_elements是否有效。假设您没有在其他地方设置_elements,这是一个主要的错误。添加:if(_elements) delete[] _elements;并确保在调用此函数之前将* _elements初始化为null。

相关问题