프로그래밍 초보자이며 한도 내에서 모든 소수를 찾을 수있는 프로그램이 있습니다. 그러나 다음과 같은 오류가 있습니다 :C - 메모리 realloc 오류
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));
}
}
[C에서 반환 malloc에'의 값()'과 친구를 캐스팅하지 마십시오 (http://stackoverflow.com/a/605858/28169). 또한 가독성을 위해'* (p + i)'의 모든 경우를'p [i]'로 바꾸어야합니다. – unwind
@unwind realloc()의 반환 값을 캐스트해야합니까? –
먼저,'* (primePtr + x)'를'primePtr [x]'로 대체하십시오. 이는 코드의 가독성을 높이기위한 것입니다. –