Timʘtei
Timʘtei

Reputation: 765

Why does realloc fails every time?

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!

Upvotes: 1

Views: 684

Answers (1)

Cherubim
Cherubim

Reputation: 5457

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?

Upvotes: 6

Related Questions