0

I seem to have trouble in extending an array using realloc...please help me out here's the code :

main() 
{
    int resultarray[] = {1},  i = 0 ,ch ;
    int *number = malloc(sizeof(int));

    printf("Enter number : ");

    while ( ch = getchar() != '\n' ) {
        number[i++] = ch-48 ;
        number = realloc(number,sizeof(int));
    }
    printf("%d",i);
}

* Error in `./a.out': realloc(): invalid next size: 0x0000000002083010 *

2 Answers2

5

Your code does not enlarge the array at all (and therefore writes beyond the allocated memory, which can cause all kinds of undefined ugly behavior ).

You probably meant something like

number = realloc(number,(i+1)*sizeof(int));

The second argument of realloc() is the new size, not the additional size.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Another issue is that `ch = getchar() != '\n'` sets `ch` to `0` or `1` each time. `!=` has higher precedence. – M.M Jul 30 '15 at 00:43
0
while ((ch = getchar()) != '\n' ) {
    number[i++] = ch-'0' ;
    number = realloc(number, (i+1)*sizeof(int));
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70