Jtechguy21
Jtechguy21

Reputation: 1

C Dynamic array that expands in size using realloc Error: Invalid next-size

I am working on a project for school below illustrates a simpler general idea of what I'm trying to achieve.

Basically What i would like to do is the following: -Ask user for a number(check!) -Create a dynamic array that stores these numbers (check!) -It will keep storing numbers until terminating value -999 is entered(check!)

My problem is this: -The professor says I may not assume the array is a certain size; -However, he does give a starting point for the size of the array which in my case is 5, which will then expand the array(double the size) as more numbers are input.

-Looking at the code below at when the user enters 6 numbers for input, the dynamic array will allocate more memory to compensate space for more integers. This part works fine.

-However, when the user enters 10 number. I would like the for the dynamic array to expand and double in size once again. However using the same method as above, this time however it fails to double in size, and gives me an error in linux while compling that says" realloc(): invalid next size: 0x000000000221f0"

Basically What i am trying to implement is a dynamic array that has a starting size of 5, and keeps allocating more size for more ints as needed. for example: dyanimic array has space for 5 ints, the user enters 5 ints. array expands space for 10 ints, the user enters 10 ints, and the array doubles again in size for 20 ints and so on.....

If someone can recommend a method for doing this, or point out my mistake I would be very appreciative.

I have spent the last 2 hours searching on here and google with possible fixes, and understanding how malloc and realloc function,but have failed thus far with a resolution.

int count=0;
int size=5;
int *to=(int *)malloc(size*sizeof(int));



printf("Enter\n");

scanf("%d",&to[count]);

while(to[count]!=(-999))
{
    count++;
    scanf("%d",&to[count]);

if(count==5)
    {
    printf("Expanding size . . . . . .\n");
    to=(int*)realloc(to,size*sizeof(int));
    }

if(count==10) 
    {
    printf("Expanding size to 10. . . . .\n");
    to=(int*)realloc(to,(2*size)*sizeof(int));
    }

}

Upvotes: 0

Views: 269

Answers (1)

abligh
abligh

Reputation: 25169

Why not just

if ((count%5) == 0)
{
    printf("Expanding size . . . . . .\n");
    to=realloc(to,count*2*sizeof(int));
}

Checking for memory allocation errors in realloc is left as an exercise for the reader.

Upvotes: 0

Related Questions