gpt4 book ai didi

C-内存重新分配错误

转载 作者:行者123 更新时间:2023-11-30 17:41:40 27 4
gpt4 key购买 nike

我是编程新手,这里有一个程序可以找出一定范围内的所有素数。但是,有一个错误:

Prime 2(1682,0x7fff76316310) malloc: *** error for object 0x1002000a0: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug'

此外,Xcode 报告了一个问题,提示“signal SIGABRT”。我怀疑这与函数“realloc”有关。到底是什么问题以及如何修复代码?谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

const int unit=3;

unsigned long* expandMem(unsigned long *primePtr, unsigned long count){
unsigned long* newPtr=(unsigned long*)realloc(primePtr, (count+unit)*sizeof(unsigned long));
return newPtr;
}


int main(){
unsigned long limit;
unsigned long count=0;
unsigned long* primePtr=(unsigned long*)malloc(sizeof(unsigned long)*unit);
*primePtr=2;

printf("Input the upper limit >>> ");
scanf("%ld",&limit);

for (unsigned long int number=3; number<=limit; number+=2) {
bool isPrime=true;
for (unsigned long i=0; (*(primePtr+i))*(*(primePtr+i))<=number; i++) {
if (number%(*(primePtr+i))==0) {
isPrime=false;
break;
}
}
if (isPrime) {
count++;
*(primePtr+count)=number;
if (count%unit==2) {
primePtr=expandMem(primePtr, count);
}
}
}
for (unsigned long i=0; i<=count; i++) {
printf("%ld ",*(primePtr+i));
}
}

最佳答案

realloc 只会为 2 个新元素分配空间,但您假设它为 3 个新元素分配空间。

建议更改(在expandMem中):

unsigned long* newPtr=(unsigned long*)realloc(primePtr, (count+1+unit)*sizeof(unsigned    long));

关于C-内存重新分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042880/

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