我一直在重新审视 C 语言,但在程序中使用后释放内存时遇到问题:
int tvalue = 2;
while (smult == 0) {
int * tvaluearray = calloc(allnum, sizeof(int));
tvaluearray = frequencyArray(tvalue, allnum, tvaluearray);
printf("tvalue = %d\n", tvalue);
//compare each index of the tvaluearray and the first array
for (int j = 0; j < allnum; j++) {
// printf("tvaluearray[%d]=%d >= firstarray[%d]=%d\n", j, tvaluearray[j], j, firstarray[j]);
if (tvaluearray[j] < firstarray[j]) {
// printf("Found the false statement\n");
break;
}
else if ( (j+1) == allnum ){
smult = 1;
// printf("Made it to else if! smult = %d\n", smult);
}
}
free(tvaluearray);
++tvalue;
}
频率数组函数如下所示:
int * frequencyArray (int target, int allnum, int targetarray[]) {
int divisor = 2;
for (int i = 0; i < allnum; i++)
targetarray[i] = 0;
//find the common factor frequency of the given number
while (target > 1) {
if (target % divisor == 0) {
targetarray[divisor] += 1;
target /= divisor;
}
else
++divisor;
}
return targetarray;
}
经过一番尝试后,我尝试了以下方法,得到了不同的结果:
1)删除targetarray的空闲:
tvalue = 1306 --> 段错误
2) 包括 free(targetarray):
t值 = 29 free():下一个尺寸无效(快) 中止(核心转储)
3) 包括 free(targetarray) 并为 tvaluearray calloc 分配 4*sizeof(int) 而不仅仅是 int:
tvalue = 31468 --> 段错误
第三个测试让我在程序遇到段错误之前更改了数组的分配空间,结果各不相同。这让我认为我分配空间的方式存在问题,但我认为这可能有点超出了我目前的理解。你们都知道我哪里可能出错了吗?
最佳答案
在 frequencyArray()
函数有一个循环:
while (target > 1) {
if (target % divisor == 0) {
targetarray[divisor] += 1;
target /= divisor;
}
else
++divisor;
}
哪里divisor
用作您的 targetarray[]
的索引。我在这里看不到 divisor
最大值的任何正式界限。 - 似乎它可以增长超过最大允许值(等于 allnum - 1
),因此 targetarray[]
之外的内存可能会被覆盖,导致内存损坏/段错误。您应该在每次迭代中检查 divisor < allnum
。
不幸的是,我不知道您的代码的上下文,因此无法在这里提出任何合适的解决方案。大概应该是这样的:
while (target > 1) {
if (target % divisor == 0) {
// 'fuse' ;)
if (divisor >= allnum) {
// place here the code needed to solve the problem or break to exit from loop
}
// end of 'fuse'
targetarray[divisor] += 1;
target /= divisor;
}
else
++divisor;
}
关于c - 段错误(循环中的 Malloc/Free),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59456602/