c++ 需要有关调整动态数组大小的帮助-检测到堆损坏[重复]

k75qkfdt  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(148)
    • 此问题在此处已有答案**:

(13个答案)
(18个答案)
3天前关闭。
我在一个C++类中动态调整数组大小时遇到了问题。
我在代码的setCoefficient函数中遇到了麻烦,我需要调整动态数组的大小,目前,当我尝试删除setCoefficient函数中的旧动态数组时,遇到了HEAP CORRUPTION DETECTED错误。
我已经评论了setCoefficient函数,并希望有人可以通过,并帮助我确定我哪里出错了。

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

sd2nnvve1#

以下是一个错误(为简洁起见,删除了cout语句):

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

for循环中的测试应该是i<p.length,而不是i<=p.length,否则,您将在polyArray末尾写入一个值,这将调用未定义的行为(可能并且经常导致崩溃)

相关问题