#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.
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.