简体   繁体   中英

Unable to extend array using realloc: “invalid next size”

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 *

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.

while ((ch = getchar()) != '\n' ) {
    number[i++] = ch-'0' ;
    number = realloc(number, (i+1)*sizeof(int));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM