0

i have a function that contains delete in it:

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;
    }
}

the class field is:

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

for some reason the first time i use the function it doesn't show any errors and work perfect but in the second time its stops in the line: "delete[] _elements;" it stops. in addition when i run this function one time it stops at the end of the object:

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

can someone help me?

Holo
  • 131
  • 8

1 Answers1

-3

You don't check that _elements is valid before you delete it. Assuming you don't set _elements somewhere else, this is a major bug. Add: if(_elements) delete[] _elements; And also make sure you initialize *_elements to be null before this function is called.

Ryan
  • 314
  • 1
  • 10