I am writing some code that inputs grid coordinates of "islands" (connected points on a grid) and finds the center of mass for each island. The code is successful for grids with a few large islands, however, it fails for grids with many small islands.
I've narrowed down the issue to rewind() failing on the 252nd loop-through. I have no idea why it fails as I've verified that island # 252 exists by printing the coordinates prior, and if I skip 252, the code fails on island 253, so I believe it is just rewind failing after 252 uses.
The code is quite large, so I'll try to just post the relevant parts:
FILE *f;
    if((f = fopen(argv[1], "r")) == NULL)
    {
            printf("Could not open file to read.\n");
            return 0;
    }
    while(!feof(f))
    {
            fscanf(f, "%d   %d      %d\n", ¤t_x, ¤t_y, &island_number);
            if(island_number > number_of_islands)
            {
            number_of_islands = island_number;
            }
    }
fclose(f);
This the first instance when f is used, but it's used again later, and again in the following for loop which is where the problem emerges:
for( int i = 0; i < number_of_islands; i++)
{
    printf("new loop: %d (number of islands: %d) \n", loop, number_of_islands);
 if(loop == 252)
 {
    printf("putting in x, y at 252...\n");
 }
This is where the code fails...
//putting numbers in x and y
    rewind(f = fopen(argv[1], "r"));
Here's a bit of the following part (probably not important):
if(loop == 252)
{
    printf("rewound at 252...\n");
    exit(0);
}
    while(!feof(f))
    {
            fscanf(f, "%d   %d      %d\n", ¤t_x, ¤t_y, &island_number);
            if(island_number == current_island_number)
            {
                    x_array[current_x] += 1;
                    y_array[current_y] += 1;
            }
    }
if(loop == 252)
{ 
    printf("finished putting in x, y at 252...\n");
    exit(0);
}
A sample of what the output looks like is this:
Everything looks good, except for the sudden segfault.
So my question is, why is rewind() suddenly segfaulting on the 252nd attempt?
 
    