编辑:问题已经解决,我正在访问由于while()条件不正确而未初始化的数据。我已将其从OR更改为AND。它现在按预期工作。谢谢!
我试图在C ++中找到两个数组之间的交集。我编写的代码可以执行我想要的操作,但是当我删除[]数组时,它会中断导致浮点异常。 (除以零?)如何在不导致程序内存泄漏的情况下保存我想要的值?
如果我省略delete []语句,这段代码完全符合我打算如何工作,但我相信这会导致内存泄漏。如果我省略语句largestIntersection = *(factorsa + i),它将返回1;我该怎么做才能在factora + i中保存值,然后删除数组以避免内存泄漏?
const int Fraction::findgcf(int a, int b) const{
a = std::abs(a); //absoute value
b = std::abs(b);
int* factorsa = new int[a]; //dynamic array of ints to store factors of a
int* factorsb = new int[b]; //dynamic array of ints to store factors of b
int numFactorsa = 0;
for(int i = 1; i <= a; i++){//iterate over the ints from 1 to a
if(a % i == 0) {//if we find a factor of a
*(factorsa + numFactorsa) = i;// and append that to the array
numFactorsa++;
}
}
int numFactorsb = 0;
for(int i = 1; i <= b; i++){
if(b % i == 0){
*(factorsb + numFactorsb) = i;
numFactorsb++;
}
}
int biggestIntersection = 1;
int i = 0, j = 0;
while(i < numFactorsa || j < numFactorsb){//while we are in the bounds of the two arrays
if(*(factorsa + i) < *(factorsb + j)){ //if the factor of a is less than the factor of b
i++; //move the index of a up one
} else if (*(factorsa + i) > *(factorsb + j)){ //if the factor of b is less than the factor of a
j++; //move the index of b up one
} else { //otherwise they must be equal
biggestIntersection = *(factorsa + i); //so that is the new biggest intersection between the sets
i++; j++;
}
}
delete [] factorsa;
delete [] factorsb;
return biggestIntersection;
最大的问题 - 可能是导致错误的原因,尽管最小的例子会让它更清楚 - 是你正在访问你尚未初始化的内存。这可能会产生不可预测的行为。
int* factorsa = new int[a];
没有将该数组中的每个int
设置为零 - 数组的内容可能实际上是任何东西。稍后,在第一个for
循环中,您可以设置某些数组位置的值,但不是全部。所以在你最后的for
循环中,你无法知道你将要输出什么。它将取决于您询问new
提供的内存位置的或多或少的随机内容。
(另外,作为评论说明,你的while
循环条件是错误的。)
你真的应该使用std :: vector。那你就不用担心清理了。
const int Fraction::findgcf(int a, int b) const{
a = std::abs(a); //absoute value
b = std::abs(b);
std::vector<int> factorsa(a);
std::vector<int> factorsb(b);
int numFactorsa = 0;
for(int i = 1; i <= a; i++){//iterate over the ints from 1 to a
if(a % i == 0) {//if we find a factor of a
factorsa[numFactorsa] = i;// and append that to the array
numFactorsa++;
}
}
int numFactorsb = 0;
for(int i = 1; i <= b; i++){
if(b % i == 0){
factorsb[numFactorsb] = i;
numFactorsb++;
}
}
int biggestIntersection = 1;
int i = 0, j = 0;
while(i < numFactorsa || j < numFactorsb){//while we are in the bounds of the two arrays
if(factorsa[i] < factorsb[j]){ //if the factor of a is less than the factor of b
i++; //move the index of a up one
}
else if (factorsa[i] > factorsb[j])
{ //if the factor of b is less than the factor of a
j++; //move the index of b up one
} else { //otherwise they must be equal
biggestIntersection = factorsa[i]; //so that is the new biggest intersection between the sets
i++; j++;
}
}
return biggestIntersection;
}