以下是我的功能。它运行正常一次,然后当第二次调用它会导致错误告诉我“双重自由或腐败”。我尝试在malloc()中添加+1,正如其他帖子所建议的那样,即使我不是存储以空字符结尾的字符串而是存储整数数组。它没有帮助。
此时我很困惑。我不明白为什么在函数结束时,free()'的指针不会超出范围,或者如果确实如此,那么当我malloc()时它如何被视为双重自由d在最后一次使用它之后自由()。
int getCount(int number) {
int totalUniqueDigits = 0;
bool* allDigits = (bool*)malloc(10 * sizeof(bool));
do {
int currentDigit = number % 10;
number /= 10;
allDigits[currentDigit] = true;
} while (number > 0);
for (int i = 0; i < 10; i += 2) {
if (allDigits[i] == true) {
totalUniqueDigits++;
}
}
free(allDigits); /*This is where the problem is, but only the second time the function is called. */
allDigits = NULL;
return totalUniqueDigits;
}
答案 0 :(得分:0)
未检查数组索引的负值。案件结案。谢谢Cris。
答案 1 :(得分:0)
如果number
为否定,那么
currentDigit = number % 10;
也将为负(如果可被10整除,则为零)。这是模数运算符的一个有点尴尬(IMO)的定义。
如果currentDigit
为否定,那么
allDigits[currentDigit] = true;
将写出界限。在大多数系统上,写入allDigits[-1]
会覆盖用于管理内存的信息。这可能不会直接导致您的程序崩溃,但稍后使用malloc
会产生这种影响。
当然,解决方案是使用abs
或将10
添加到currentDigit
,如果它是否定的。
答案 2 :(得分:0)
您发布的代码运行时所有正整数都没有错误。它是C ++代码,而不是C代码。 如果是C代码,则需要显示“bool”,“true”和“false”的声明, 否则在提供的函数内部没有错误,执行明智。
这是一个完整的C ++程序来测试它。
#include <iostream>
using namespace std;
int getTotalUniqueEvenDigitCount(int number) {
int totalUniqueDigits = 0;
bool* allDigits = (bool*)malloc(10 * sizeof(bool));
do {
int currentDigit = number % 10;
number /= 10;
allDigits[currentDigit] = true;
} while (number > 0);
for (int i = 0; i < 10; i += 2) {
if (allDigits[i] == true) {
totalUniqueDigits++;
}
}
free(allDigits); /*This is where the problem is, but only the second time the function is called. */
allDigits = NULL;
return totalUniqueDigits;
}
int main(int argc, char ** argv){
cout << getTotalUniqueEvenDigitCount(stoi(argv[1]));
return 0;
}
将其测试为
$<progname> number