Search code examples
cfilesegmentation-fault

fgets and Segmentation Fault


I got this function:

#define DIGITS_MAXIMUM_NUMBER 10

int* read_from_file(const char* file_name)
{
        int limit = 101;
        int *values = (int *) malloc(sizeof(int) * limit);
        FILE *fp = fopen(file_name, "r");
        char string_value[DIGITS_MAXIMUM_NUMBER];
        int i = 1;

        while(fgets(string_value, DIGITS_MAXIMUM_NUMBER, fp) != NULL)
        {
                if (i >= limit) {
                        limit += 100;
                        values = realloc(values, limit);
                }

                values[i] = atoi(string_value);
                i++;
                if ( i >= 106 )
                        printf("%d\n", i);
        }

        values[0] = i;

        if (i != limit)
                values = realloc(values, i);

        fclose(fp);
        return values;
}

I get Segmentation fault at the 106th iteration, so it means that the loop works, but at that certain iteration, when fgets is executed, Segmentation fault is raised.

If anybody knows why or have at least an opinion, it would be great to share, thanks.


Solution

  • Immediate solution:

    // values = realloc(values, limit);
    values = realloc(values, sizeof *values * limit);
    

    There's a lot more you can improve though!