【发布时间】:2019-04-12 22:46:09
【问题描述】:
编辑:问题已解决,我正在访问由于不正确的 while() 条件而未初始化的数据。我已将其从 OR 更改为 AND。它现在按预期工作。谢谢!
我试图在 C++ 中找到两个数组之间的交集。我已经编写了可以满足我要求的代码,但是当我删除 [] 数组时它会中断,从而导致浮点异常。 (除以零?)如何保存我想要的值,而不会导致程序中的内存泄漏?
如果我省略 delete[] 语句,此代码将完全按照我的预期工作,但我相信这会导致内存泄漏。如果我省略语句 maxIntersection = *(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;
【问题讨论】:
-
你的条件错误
while(i < numFactorsa || j < numFactorsb){循环只要其中一个计数器在界限内(你想要两个)。但是,要知道这是否会导致问题,请添加 minimal reproducible example -
new[]比您在这里发现的价值要麻烦得多。了解如何有效地使用像std::vector这样的标准库容器,而不是使用new[]对 C 样式数组进行原始分配。在 C++ 中,您 100% 负责内存管理,因此进行手动分配意味着在正确的时间和地点小心添加相应的delete[]调用。标准库容器可以为您处理。 -
@tadman 是的,我有一个用向量制作的这个函数的版本,它工作得很好,但是我不应该使用容器来完成这个任务。
-
需要注意的一点是,您可以像使用数组一样使用指针,而且它更具可读性:
*(x + y)变为x[y],*(x + y) = z变为x[y] = z。这有助于避免由杂乱的代码引起的简单错误。 -
@tadman 很重要的一点,在多维数组方面更容易处理,我不知道两者都产生了相同的编译代码。谢谢
标签: c++ pointers memory-leaks dynamic-arrays