gpt4 book ai didi

c - realloc 指针指向随机内存,导致程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:26 25 4
gpt4 key购买 nike

我在第二个函数中的 realloc 语句运行到一个点,然后指针似乎突然指向随机内存。有人可以解释一下我该如何解决这个问题吗?查看输出可能会节省一些时间。谢谢。

int main()
{

int testCases, i, n;
int* primeArray;
int* size;

primeArray = malloc(sizeof(int));
primeArray[0] = 2;
size = 1;

int number = 2;
while(number < 1000){
number = nextPrime(number, primeArray, &size);
printf("Prime Array at %d is %d, size is %d, number is %d \n", 0, primeArray[0], size, number);
}


scanf("%d", &testCases);
for(i = 0; i < testCases; i++){
scanf("%d", n);

}

free(primeArray);
free(size);
return 0;
}

第二个函数:

int nextPrime(int number, int* primeArray, int* size){
int foundPrime = 0, num = number, i;
while(!foundPrime){
num++;
int allNums = 0;
//printf("Size: %d \n", *size);
for(i = 0; i < *size; i++){
//printf("%d mod %d \n", num, primeArray[i]);
if(num % primeArray[i] != 0){
allNums += 0;
}
else {
allNums = 1;
break;
}
}
if(allNums == 0){
*size+=1;
//printf("Size: %d \n", *size);
foundPrime = 1;
primeArray = realloc(primeArray, *size * sizeof(int) );
primeArray[*size-1] = num;
//printf("%d \n", primeArray[*size-1]);
return num;
}
}
}

输出:

Prime Array at 0 is 2, size is 2, number is 3  
Prime Array at 0 is 2, size is 3, number is 5
Prime Array at 0 is 2, size is 4, number is 7
...
Prime Array at 0 is 2, size is 94, number is 491
Prime Array at 0 is 2, size is 95, number is 499
Prime Array at 0 is 2, size is 96, number is 503
Prime Array at 0 is 16852008, size is 97, number is 509

最佳答案

primeArray,即使它是一个指针,也会按值传递给您的 nextPrime 函数。因此,如果 realloc 更改指针值(它可以而且经常会这样做),main 不会在 nextPrime 时将该值反射(reflect)回它返回。一个快速的解决方法是更改​​您的 nextPrime 以获取指向指针参数的指针,而不仅仅是数组指针。

这是一个快速修复,我修改了 nextPrime 的函数签名,并在函数的开始和结束处添加了代码。

int nextPrime(int number, int** ptrToPrimeArray, int* size){

int* primeArray = *ptrToPrimeArray; // primeArray is the deferenced value of ptrToPrimeArray

int foundPrime = 0, num = number, i;
while(!foundPrime){
num++;
int allNums = 0;
//printf("Size: %d \n", *size);
for(i = 0; i < *size; i++){
//printf("%d mod %d \n", num, primeArray[i]);
if(num % primeArray[i] != 0){
allNums += 0;
}
else {
allNums = 1;
break;
}
}
if(allNums == 0){
*size+=1;
//printf("Size: %d \n", *size);
foundPrime = 1;
primeArray = realloc(primeArray, *size * sizeof(int) );
primeArray[*size-1] = num;
//printf("%d \n", primeArray[*size-1]);

*ptrToPrimeArray = primeArray; // return the changed value of primeArray back to the caller

return num;
}
}
}

然后在 main 中调用它,如下所示:

number = nextPrime(number, &primeArray, &size);

关于c - realloc 指针指向随机内存,导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com