Search code examples
cpointersmemory-managementrealloc

C - memory realloc error


I'm new to programming and here's a program that can find out all the prime numbers within a limit. However, there is an error that says:

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'

Also, Xcode reports an issue says 'signal SIGABRT'. I suspect that is has something to do with the function 'realloc'. What exactly is the problem and how to fix the code? Thanks!

#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));
}
}

Solution

  • The realloc will only allocate space for 2 new elements but you assume it allocates space for 3 new elements.

    Suggested change (in expandMem):

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