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!

3
  • Failure to include <stdlib.h> and the cast to the result of realloc make all the difference. Commented May 7, 2017 at 17:58
  • @pmg i have included <stdlib.h> and i do not understand what`s wrong with realloc Commented May 7, 2017 at 18:03
  • Without <stdlib.h> 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. Commented May 7, 2017 at 18:17

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.