-2

I am having trouble dynamically resizing an array in one of my C++ classes.

I am specifically having trouble inside the setCoefficient function of my code, where I need to resize a dynamic array. Currently, I am running into an error of HEAP CORRUPTION DETECTED when I try and delete the old dynamic array in the setCoefficient function.

I have commented the setCoefficient function and was hoping someone could go through and help me determine where I am going wrong.

void Poly::setCoefficient(const int coefficient, const int power) {
    if (power > this->length) {
        //we need to resize the array we currently have.

        //Here I am creating a new array that will temporarily store larger values
        int* resizedArray = new int[power * 2];

        //This for loop assigns all the values in the current object's array to the new array (resizedArray)
        for (int i = 0; i < this->length; i++) {
            resizedArray[i] = this->polyArray[i];
        }

        //Here I am adding the term that we wanted to add in the first place with setCoefficient
        resizedArray[power] = coefficient;

        //Deleting the terms in polyArray
        delete [] this->polyArray;
        
        //Creating a new array that has been resized
        this->polyArray = new int[power * 2];
        
        //Setting the values of the temporary array, resizedArray, to the array of the current object.
        this->polyArray = resizedArray;
        
        //modifying the length of the current object.
        this->length = power * 2;
    }
    else {
        this->polyArray[power] = coefficient;
    }
}
  • 2
    *"//I think I need to add 1 here to account for that fact that arrays start at index 0."* -- if you know what you need to do, why don't you do it? – JaMiT Jan 10 '21 at 23:51

1 Answers1

1

One error is here (cout statements removed for brevity):

this->length = p.length;
this->polyArray = new int[this->length];
for (int i = 0; i<=p.length; i++) {
    this->polyArray[i] = p.polyArray[i];
}

The test in your for-loop should be i<p.length rather than i<=p.length. Otherwise you are writing one value past the end of polyArray, which invokes undefined behavior (which can and often does result in a crash)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234