-1

I need to find all the prime factors of a number. I have written this code, but when I try to reallocate the pointer array in calculatePrimes function using realloc, gcc gives error that i have not allocated the pointer before using realloc. I know I can pass the double pointer and use malloc inside the calculatePrimes function or, use a single pointer and return the value.

Code:

#include "stdio.h"
#include <math.h>
#include <stdlib.h>

void calculatePrimes(int max, int** array){
    int size=1, i;
    *array[0]=2;
    for(i=0; i<max; i++){
        if(isPrime(i)){
            *array = (int *)realloc(**array, (++size)*sizeof(int));
            *array[size-1]=i;
        }
    }
}

int isPrime(int value){
    int i=2, root = sqrt(value);
    for(;i<root;i++){
        if(value%i==0) return 0;
    }
    return 1;
}


void main(int argc, char*argv[]){
    int input = atoi(argv[1]), numPrimes;
    int *primes=(int *)malloc(sizeof(int));
    calculatePrimes(input, &primes);
    numPrimes=sizeof(primes)/sizeof(int);
    printf("%d\n", numPrimes);
    free(primes);
}
user1242145
  • 11
  • 1
  • 4
  • You should show the exact error, since your re-phrasing ("gcc is giving error that I have not allocated the function before") doesn't make a lot of sense. Functions are not allocated ... – unwind Apr 25 '13 at 07:02
  • Don't cast the return value of malloc or realloc, it can hide certain subtle errors from you. – paxdiablo Apr 25 '13 at 07:04

1 Answers1

3

Incorrect usage of realloc(). The correct is below:

*array = realloc(*array, (++size)*sizeof(int));

When you pass **array to realloc() you pass the value of the first element of the array that is int instead of int*.

Note that I've also removed the cast. In C, it's not needed and can hide certain problems you don't want hidden. Specifically, it can give you the wrong function signature for malloc/realloc which, if your int and void* type aren't compatible, can lead to corrupted pointers.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Alex
  • 9,891
  • 11
  • 53
  • 87
  • Please consider [not casting the return value of `malloc()`](http://stackoverflow.com/a/605858/28169). – unwind Apr 25 '13 at 07:02