- 此问题在此处已有答案**:
(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;
}
}
1条答案
按热度按时间sd2nnvve1#
以下是一个错误(为简洁起见,删除了
cout
语句):for循环中的测试应该是
i<p.length
,而不是i<=p.length
,否则,您将在polyArray
末尾写入一个值,这将调用未定义的行为(可能并且经常导致崩溃)