Question

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

int main ( int argc, char * argv [] ) {
  int alloc = 10;
  int i = 0;
  int *array = (int *) malloc (alloc * sizeof(*array));

  printf("Enter some integers, stops with EOF:\n");

  while( 1 ) {
    if( i > alloc - 1 ) {
        alloc *= 2;
        array = (int *) realloc (array, alloc * sizeof(*array)); 
    }

    if( scanf("%d", &array[i]) != 1 ) 
      break;

    i++;
  }

  if( ! feof(stdin) ) {
      printf("Wrong input.\n");
      return 1; 
  }

  free(array);

  return 0;
}

I'd like to ask about the right way of using realloc.

The above code works fine. The array is dynamically expanding according to the input.

However, I heard that the right way to do this is by using a temporary array and I'd like to know why and how to do it.

Was it helpful?

Solution

int *temp;
temp = (int *) realloc (array, alloc * sizeof(*array)); }
if(temp == NULL){free(array);}
else{
    array = temp;
    //continue
}

In your original code:

array = (int *) realloc (array, alloc * sizeof(*array)); }

if realloc fails array = NULL. You lost your pointer. You cant do free(array); any more.

OTHER TIPS

Ok so the original code is wrong because I would lose a pointer as Valter says.

array = (int *) realloc (array, alloc * sizeof(*array)); } //wrong

But if I try Valters code the program would crash. See comments below.

int *temp;
temp = (int *) realloc (array, alloc * sizeof(*array)); } //Here ends body of condition
if(temp == NULL){free(array);}                            //for expanding array

else{                //Lets say we are in firts iteration. temp is not equal NULL
     array = temp;   //so we ran in the "else" where we try to asign temp to
     //continue      //array. But theres nothing in temp yet => Program crashes.
}

So I made a little change of code above which works well.

if( i > alloc - 1 ) {
    alloc *= 2;
    temp = (int *) realloc (array, alloc * sizeof(*array));

    if( temp == NULL ) {
        free(array);
        printf("Error allocating memory.\n");
        return 1; }

    array = temp; //Now we have confidence that temp would not be empty or what so ever
 } //Here ends body of condition for expanding array
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top