Notice if you use the same pointer as an argument and return to realloc() call you can end up with a memory leakage if realloc() fails. It is wise to use different pointers. Your code, changed a little bit:
Code:
#include <stdio.h>
#include <stdlib.h>
int push_int( int **array, size_t *counter, int value )
{
int *p;
if ( ! ( p = realloc( *array, ( *counter + 1 ) * sizeof value ) ) )
return 0;
p[( *counter )++] = value;
*array = p; // update the pointer!
return 1;
}
int main( int argc, char *argv[] )
{
int *array;
char *line;
size_t len, counter;
int number;
if ( !( array = malloc( sizeof * array ) ) )
{
fputs( "ERROR allocating initial array.\n", stderr );
return EXIT_FAILURE;
}
line = NULL;
len = 0;
counter = 0;
// getline() will allocate a buffer for the line. This buffer must be freed
// before calling getline() again!
while ( getline( &line, &len, stdin ) != -1 )
{
if ( sscanf( line, "%d", &number ) != 1 )
{
fputs( "ERROR geting integer value.\n", stderr );
free( line );
free( array );
return EXIT_FAILURE;
}
number = atoi( line );
// free allocated line and prepare for next read.
free( line );
line = NULL;
len = 0;
if ( ! push_int( &array, &counter, number ) )
{
fputs( "ERROR pushing value.\n", stderr );
free( array );
return EXIT_FAILURE;
}
}
// ... dosomething with the array here...
// ...
// Finally free the array and return with success.
free( array );
return EXIT_SUCCESS;
}