1

I have a problem in the code. malloc works and in the while-loop, realloc() works for the first time and when it is called the second time it always fails. The code is part of an algorithm to get the prime factors of a number.

int main()
{
    int n, in, *ar, len = 0;
    scanf("%d", &n);
    ar = (int *) malloc(1 * sizeof(int));
    while(n % 2 == 0){
        ar[len] = 2;
        len++;
        ar = (int *) realloc(ar, len * sizeof(int));
        if(ar == NULL){
            printf("Error");
            return 1;
        }
        n /= 2;
    }
    return 0;
}

I tried with len initialized to 1 but it still fails. It is strange it does not fail on the first call but it fails on the second call. I have read other similar questions but I am a beginner and I didn`t understand. Thanks in advance!

Cherubim
  • 5,287
  • 3
  • 20
  • 37
Timʘtei
  • 753
  • 1
  • 8
  • 21
  • Failure to include `` and the cast to the result of `realloc` make all the difference. – pmg May 07 '17 at 17:58
  • @pmg i have included and i do not understand what`s wrong with realloc – Timʘtei May 07 '17 at 18:03
  • Without `` included, the compiler assumes `realloc` returns an int then, with the cast, converts that int to a pointer. First: `malloc` returns a pointer and interpreting that pointer as an int may change the value. Second: converting an (invalid) int to a pointer is an invalid conversion; the cast makes the compiler accept it without a warning. – pmg May 07 '17 at 18:17

1 Answers1

6

Here in your program, you are accessing an array out of bounds. which leads to undefined behaviour.

initially, when len = 0, in the while loop:

ar[len] = 2;  //ar[0] = 2;
len++;        //len = 1
ar = (int *) realloc(ar, len * sizeof(int));
//ar is of size 1

then in next iteration, when len = 1

ar[1] = 2; //you cannot access ar[1] as size of `ar` is only 1.

this continues with each iteration. To avoid this do:

//initialize len to 1
int len = 1;

and use ar[len-1] instead of ar[len] in the while loop.

Have a look at this: How dangerous is it to access an array out of bounds?

Community
  • 1
  • 1
Cherubim
  • 5,287
  • 3
  • 20
  • 37